action performed when an option from a JComboBox is chosen

15,940

Solution 1

Why not simply use an ActionListener as the combo box tutorial suggests? Either that or an ItemListener which is also mentioned in the tutorial. The tutorial also advises strongly not to use a MouseListener.

A general lesson to get from this question is: look at the Java tutorials as you'll often get the answer to your question quicker than you can get here, and with decent sample code too!

Luck.

Solution 2

I'd suggest an ItemListener .

comboBoxMode = new JComboBox();

comboBoxMode.addItemListener(this);
...
public void itemStateChanged(ItemEvent e) {
    if ((e.getStateChange() == ItemEvent.SELECTED)) {
       int selection = comboBoxMode.getSelectedIndex();
            switch (selection){
            case 0:  break;
            case 1:  enableNormalModeFeatures(); break;
            case 2:  enableRevisionModeFeatures(); break;
            case 3:  enableTimerModeFeatures(); break;
     }
}

Solution 3

try to apply a normal actionlistener:

class ComboListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            AbstractButton abstractButton =(AbstractButton)e.getSource();
            ButtonModel buttonModel = abstractButton.getModel();
            //buttonModel.isSelected()
        }

    }
Share:
15,940
user1058210
Author by

user1058210

Updated on June 04, 2022

Comments

  • user1058210
    user1058210 about 2 years

    Hi I have a JComboBox with 3 options, and I'm trying to figure out which actionlistener to apply in order for something to happen when an option is selected. At the moment my code is:

    comboBoxMode = new JComboBox();
        comboBoxMode.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                int selection = comboBoxMode.getSelectedIndex();
                switch (selection){
                case 0:  break;
                case 1:  enableNormalModeFeatures(); break;
                case 2:  enableRevisionModeFeatures(); break;
                case 3:  enableTimerModeFeatures(); break;
                }
            }
        });
        comboBoxMode.setModel(new DefaultComboBoxModel(new String[] {"[--Please Select a Mode--]", "Normal", "Revision", "Timer"}));
    

    The purpose is to enable other selection tools on the page when they choose a particular mode. mouselistener does not seem to be working. What confused me is that you actually have to click twice to select an option, but I'm assuming that there is some inbuilt code to only run if a list item has been selected? Anyway, any pointers would be appreciated, thanks guys!

  • mKorbel
    mKorbel over 12 years
    +1 please add if ((e.getStateChange() == ItemEvent.SELECTED)) {