gpt4 book ai didi

java - Swing Jcombobox 将第一个元素设置为默认选中

转载 作者:行者123 更新时间:2023-11-29 05:03:08 25 4
gpt4 key购买 nike

    String[] bookArray={"a","b","c"};
JComboBox bookComboBox = new JComboBox(bookArray);
bookComboBox.setSelectedIndex(0);
bookComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb= (JComboBox) e.getSource();
bookNameSelected=(String) cb.getSelectedItem();
System.out.println("book name selected:"+bookNameSelected);
}
});

下拉列表的第一个元素显示为默认值,但如果用户未选择任何值,则不会作为默认选择值传递。

最佳答案

ActionListener注册之后移动bookComboBox.setSelectedIndex(0);,这允许触发ActionListener并设置bookNameSelected

String[] bookArray = {"a", "b", "c"};
JComboBox bookComboBox = new JComboBox(bookArray);
bookComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
bookNameSelected = (String) cb.getSelectedItem();
System.out.println("book name selected:" + bookNameSelected);
}
});
bookComboBox.setSelectedIndex(0);

关于java - Swing Jcombobox 将第一个元素设置为默认选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31377479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com