user1058210
user1058210

Reputation: 1689

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!

Upvotes: 2

Views: 17136

Answers (3)

COD3BOY
COD3BOY

Reputation: 12092

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;
     }
}

Upvotes: 5

Anthea
Anthea

Reputation: 3809

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()
        }

    }

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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.

Upvotes: 4

Related Questions