Vassilis De
Vassilis De

Reputation: 373

setSelectedItem in JComboBox by firing event

I have a JComboBox

JComboBox tableChoose = new JComboBox();
tableChoose.addItem("Bill");
tableChoose.addItem("Bob");
tableChoose.setSelectedItem("Bill");

and some handling methods

public void addComboActionListener(IComboHandler handler){
    tableChoose.addActionListener(handler);
}

public Object getTableChooseSelectedItem(){
    return tableChoose.getSelectedItem();
}

public void actionPerformed(ActionEvent event) {
    JOptionPane.showMessageDialog(null, fileReaderWindow.getTableChooseSelectedItem() , null, JOptionPane.ERROR_MESSAGE);
}

As you see, I set "Bill" as first selected item. When I run the program, I have to reselect "Bill" in order to fire the event in actionPerfomed.

Is there a way to fire the event without reselecting the item in JComboBox? Thank you in advance.

Upvotes: 0

Views: 1792

Answers (2)

mxb
mxb

Reputation: 3330

Use the actionPerformed() method passing a dummy ActionEvent. For example:

tableChoose.actionPerformed(new ActionEvent(tableChoose, 0, ""));

the parameter should be ignored and the fireActionEvent() method should be triggered.

Warning this suggestion was devised looking at the source code for JComboBox. The comments state to not call this method directly so you would do this at you own risk as the implementation could change in the future.

Further look at the source code didn't show up any other ways to fire the notification besides calling the setSelectedItem() method.

Upvotes: 1

BackSlash
BackSlash

Reputation: 22233

Add the action listener before setting the selected item:

JComboBox<String> b = new JComboBox<String>();

b.addItem("A");
b.addItem("B");
b.addItem("C");

b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        JComboBox<String> src = (JComboBox<String>) e.getSource();
        System.out.println("ActionListener called. '"+src.getSelectedItem()+"' selected.");
    }
});

b.setSelectedItem("A");

Output:

ActionListener called. 'A' selected.

Upvotes: 3

Related Questions