Swing Jcombobox 将第一个元素设置为默认选中
Swing Jcombobox set first element as default selected
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);
}
});
下拉列表的第一个元素显示为默认值,但如果用户没有select任何值,则不会作为默认值传递select。
在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);
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);
}
});
下拉列表的第一个元素显示为默认值,但如果用户没有select任何值,则不会作为默认值传递select。
在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);