0

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Vassilis De
  • 363
  • 1
  • 3
  • 21
  • Did you try adding the listener before setting the selected item? – BackSlash Jul 14 '14 at 15:52
  • Probably [fireActionEvent](http://docs.oracle.com/javase/6/docs/api/javax/swing/JComboBox.html#fireActionEvent%28%29) – gtgaxiola Jul 14 '14 at 15:52
  • @gtgaxiola It's `protected`, you can't call it unless you make your class extend `JComboBox` (which is not the OP's scenario). – BackSlash Jul 14 '14 at 15:57
  • [Mark Peters](http://stackoverflow.com/questions/4753004/how-do-i-programatically-send-actionevent-to-jbutton) answer is the best approach of what you are trying to do – gtgaxiola Jul 14 '14 at 17:39

2 Answers2

3

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.
BackSlash
  • 21,927
  • 22
  • 96
  • 136
1

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.

mxb
  • 3,300
  • 4
  • 20
  • 25
  • It's a `protected` method, you can use it only if your class is in the same package as the one that contains the method. So the OP won't be able to call it without extending `JComboBox`. – BackSlash Jul 14 '14 at 15:54
  • thanks @BackSlash, I revised the answer changing the suggested method – mxb Jul 14 '14 at 16:06