我正在做一个testJComboBox程序。选择jCombobox的输出后,我将获得所需的字符串值。但是,它不起作用。
这是我的代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TestJCB extends JFrame {
private JLabel genderL;
private JComboBox genderJCB;
private String[] test = {"male", "female"};
private JButton gB;
public TestJCB() {
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setVisible(true);
JPanel frame = new JPanel();
frame.setSize(400, 400);
frame.setLocation(0, 0);
frame.setLayout(null);
frame.setVisible(true);
JLabel genderL = new JLabel("Gender");
genderL.setBounds(10, 200, 100, 30);
JComboBox genderJCB = new JComboBox(test);
genderJCB.setBounds(60, 10, 100, 30);
JButton gB = new JButton("Gender");
gB.setBounds(10, 50, 60, 30);
aaa a = new aaa();
gB.addActionListener(a);
frame.add(genderL);
frame.add(genderJCB);
frame.add(gB);
add(frame);
}
public class aaa implements ActionListener {
public void actionPerformed(ActionEvent sHandler) {
if (genderJCB.getSelectedItem().equals("female")) {
System.out.print("yes");
} else {
System.out.print("no");
}
}
}
public static void main(String[] args) {
TestJCB test = new TestJCB();
test.setVisible(true);
}
}
我也尝试过
combo.getEditor().getItem()
,但是没有用。 最佳答案
我也尝试了combo.getEditor()。getItem(),但是没有用。
您最重要的问题是,声明从未使用过或初始化过的变量
private JComboBox genderJCB;
因为里面的公共
TestJCB(){
覆盖并创建了JComboBox genderJCB = new JComboBox(test);// same issue with JLabel too
如果您想使用
ActionPerformed
进行监听,请将其更改为genderJCB = new JComboBox(test);
最好是读JComboBox tutorial