这是我的 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);
希望这有帮助,如果没有帮助,请用更完整的示例更新您的问题,以按照安德鲁的建议澄清问题
关于java - setSelectedIndex(-1) 不适用于 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643483/