我在做一個testJComboBox程序。一旦我選擇jCombobox的輸出,我會得到我需要的字符串值。但是,它不起作用。從java中的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()
,但沒有奏效。
歡迎在這個論壇 – mKorbel
沒有做任何手工上漿/定位(又名:零或absoluteLayout)永遠!相反,請使用合適的LayoutManager。 – kleopatra
@kleopatra,使用空佈局不合適嗎?我應該重新編碼我的GUI併爲我的程序使用合適的LayoutManager? – NOOBprogrammer