setSelectedIndex(-1) 不适用于 JComboBox

setSelectedIndex(-1) not working for JComboBox

所以这是我的 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

的建议澄清问题