Reputation: 1689
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
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
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
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