簡體   English   中英

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);

希望這會有所幫助,如果不能解決問題,請使用更完整的示例更新您的問題,以闡明問題,如安德魯建議的那樣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM