Search code examples
javaswingjcomboboxactionlistener

action performed when an option from a JComboBox is chosen


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!


Solution

  • 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.