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);
}
});
下拉列表的第一个元素显示为默认值,但如果用户未选择任何值,则不会作为默认选择值传递。
答案 0 :(得分:3)
在注册bookComboBox.setSelectedIndex(0);
后移动ActionListener
,这样可以触发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);