这是我的Java Swing UI代码。基本上我有2个组合框,并且我试图将两者的默认索引都设置为-1(空白)。第一个setSelectedIndex(-1)
工作正常,但第二个工作不正常。与ActionListener
第一个有关吗?但是将其向下移动也不起作用。
public Panel(JFrame parent) {
this.setBounds(0, 0, 0, 0);
this.setBorder(new EmptyBorder(5, 5, 5, 5));
this.setLayout(null);
...
// This is working
fstCB = new JComboBox(SomeEnum.values());
fstCB.setSelectedIndex(-1);
fstCB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do something
}
}
});
fstCB.setEditable(true);
this.add(fstCB);
// This is not working.
JComboBox<String> sndCB = new JComboBox<String>();
sndCB.setSelectedIndex(-1);
sndCB.setVisible(false);
this.add(sndCB);
List<String[]> rs = db.select("SELECT smth FROM table", 1);
for (String[] r : rs) {
sndCB.addItem(r[0]);
}
JCheckBox chckbx = new JCheckBox("Check here");
chckbx.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (chckbx.isVisible()) {
chckbx.setVisible(false);
} else {
chckbx.setVisible(true);
}
}
});
this.add(chckbx);
}
提前致谢。
快速浏览一下,问题似乎出在您设置索引时,而不是听众的使用情况上
在您提供的代码中,JComboBox在设置索引之前有问题,因为该索引中没有任何项目。然后从结果集中添加项目时,它将恢复为选择第一个项目的默认行为
我在下面添加了一个简单的示例来突出显示这一点
enum SomeEnum{
One, Two, Three;
}
public static void main(String[] args){
JFrame frame = new JFrame();
JComboBox prePopulatedComboBox = new JComboBox(SomeEnum.values());
prePopulatedComboBox.setSelectedIndex(-1);
JComboBox postPopulatedComboBox = new JComboBox();
postPopulatedComboBox.setSelectedIndex(-1);
for(SomeEnum someEnum : SomeEnum.values()){
postPopulatedComboBox.addItem(someEnum);
}
//Uncomment the below line to see the difference
//postPopulatedComboBox.setSelectedIndex(-1);
JPanel panel = new JPanel(new BorderLayout(5,5));
panel.add(prePopulatedComboBox, BorderLayout.NORTH);
panel.add(postPopulatedComboBox, BorderLayout.SOUTH);
frame.add(panel);
frame.setMinimumSize(new Dimension(250,250));
frame.setVisible(true);
}
我的建议是尝试移动:
sndCB.setSelectedIndex(-1);
到这里:
List<String[]> rs = db.select("SELECT smth FROM table", 1);
for (String[] r : rs) {
sndCB.addItem(r[0]);
}
sndCB.setSelectedIndex(-1);
希望这会有所帮助,如果不能解决问题,请使用更完整的示例来更新您的问题,以阐明问题,如安德鲁(Andrew)所建议
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句