Search code examples
javaswingevent-handlingitemscontroljcombobox

How can i make an event to a JComboBox which triggers AFTER selection?


I want to make an event which will be triggered after i make the selection to the JComboBox. the problem I'm now facing is that when i added an ActionListener, it was triggered when the user clicked on the box but BEFORE he actually chose the new item, thus the action listener was activated all the time on the previous value which was selected in the box. what i want to do is simply changing the title of an JTextArea according to the selection. I tried doing something like this:

 jBox.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
    String alt = GetAlgoAreaTitleByChoice();
    panel.remove(jArea);
    currentBest = setArea("",alt);
    currentBest.setBounds(50, 350, 1000, 290);
    panel.add(jArea);
     }
     });

and the method inside:

private String GetArgsAreaTitleByChoice(){
    String chi = jBox.getSelectedItem().toString();
    if(chi.equals(generalChoice)){
    return "Hello";
    }
    else if(chi.equals(algoChoice)){
    return "World";
    }
    else if(chi.equals(argsChoice)){
    return "Hello";
    }
    return null;
}

I've tried using the SELECTED events now like this:

public void itemStateChanged(ItemEvent e) {
JComboBox cb = (JComboBox)e.getSource();

    // Get the affected item
    String item = cb.getSelectedItem().toString();

    if (e.getStateChange() == ItemEvent.SELECTED) {
        panel.remove(jBox);
    textArea = setArea("", item);
        panel.add(jBox);
   }

but it seems to remove the area from the panel without adding it back... why is this happening?


Solution

  • For listening of events from JComboBox is better implements ItemListener, returns two events SELECTED/DESELECTED

    EDIT

    if you remove/add JComponent(s) on Runtime and in already visible container, then you have to call (as least code lines)

    revalidate();
    repaint();