我有点卡住了。我想不出比这更大的问题,所以我要找到根源,最终建立自己的道路!
我无法在组合框中打印所选项目,目前我有一个ActionListener
:
box.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
myBox(evt);
}
});
...
protected void myBox(ActionEvent evt)
{
if(myBoxName.getSelectedItem().toString() != null)
System.out.println(myBoxName.getSelectedItem().toString());
}
我希望每次更改所选项目时都能将其打印到控制台,但事实并非如此。不过这应该很简单!
谢谢
最佳答案
我刚刚尝试了您的代码,它运行良好。每当我更改选择时,所选文本都会写入 System.out
。
我唯一改变的是检查 myBoxName.getSelectedItem().toString() != null
,我检查 myBoxName.getSelectedItem() != null
反而。不过,这应该与您的问题无关。
public class ComboBoxTest {
private JComboBox comboBox = new JComboBox(
new DefaultComboBoxModel(new String[] { "Test1", "Test2", "Test3" }));
public ComboBoxTest() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(200, 100);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
myBox(evt);
}
});
frame.getContentPane().add(comboBox);
frame.setVisible(true);
}
protected void myBox(ActionEvent evt) {
if (comboBox.getSelectedItem() != null) {
System.out.println(comboBox.getSelectedItem().toString());
}
}
}
关于java - ComboBox - 打印出所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4024392/