Search code examples
javaswingactionlistenerjcombobox

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

First element of drop down is shown as default but not passed as default selected value if user does not select any value.


Solution

  • Move bookComboBox.setSelectedIndex(0); after the registration of the ActionListener, this allows the ActionListener to be triggered and sets the 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);