我有一個JComboBox顯示在下面的代碼。當程序啓動時,actionPerformed事件立即引發一些空指針異常,所以我想從沒有選中的元素開始。但是,由於某種原因,它不起作用(無論我做什麼,它始終始終顯示「USD/TRY」)。任何人有任何想法?固執JComboBox
JComboBox comboBox = new JComboBox(new String[]{"USD/TRY", "EUR/TRY", "GBP/TRY"});
comboBox.setSelectedIndex(-1); // doesnt change anything
comboBox.setSelectedIndex(2); // doesnt change anything
comboBox.setSelectedItem(null); // doesnt change anything
UPDATE:構建組合框像下面並沒有改變任何東西要麼
JComboBox comboBox = new JComboBox();
comboBox.addItem("USD/TRY");
comboBox.addItem("EUR/TRY");
comboBox.addItem("GBP/TRY");
這裏是SSCCE:
public class MainFrame {
private final JTextArea textArea = new JTextArea();
private IExchangeSource s;
public MainFrame(final IExchangeSource s) {
//build gui
final JComboBox comboBox = new JComboBox();
comboBox.addItem("USD/TRY");
comboBox.addItem("EUR/TRY");
comboBox.addItem("GBP/TRY");
comboBox.setSelectedIndex(-1); // doesnt change anything
//comboBox.setSelectedIndex(2); // doesnt change anything
JFrame f = new JFrame("Currency Converter");
JPanel p = new JPanel(new BorderLayout());
textArea.setName("textarea");
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
this.s = s;
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String exchange = (String) comboBox.getSelectedItem();
s.getData(exchange);
}
});
p.add(comboBox, BorderLayout.NORTH);
p.add(textArea, BorderLayout.CENTER);
f.setPreferredSize(new Dimension(300, 300));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.add(p);
comboBox.setSelectedIndex(0);
f.setVisible(true);
}
}
嘗試在創建JComboBox之後加載String []? – 2012-01-04 16:21:26
試過,它不工作= /我相應地更新了問題。謝謝 – Cemre 2012-01-04 16:26:37
有異常的堆棧跟蹤會有所幫助。你怎麼能添加一個ActionListener到一個尚未創建的組合框? – 2012-01-04 16:30:32