Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

java - JComboBox Action listener

I'm having this problem. I have multiple JComboBoxes (5 total).

To each comboBox I add an ActionListener, but the same ActionListener for all of them, called:

ComboBoxActionPerformed(java.awt.event.ActionEvent e)

and when that action is performed I look at the event (e) and do:

JComboBox c = ((JComboBox)e.getSource());
//DO WORK relating to c as thats the combobox that triggered.

but the problem is when I change something in any of my comboboxes the Action is always triggered by the last combo box to which I am attaching the actionlistner.

anyone have any idea?

I then switched to ItemListner. This is what im doing a

class MyActionListner implements ItemListener 
{
    //STUFF
        @Override
        public void itemStateChanged(ItemEvent evt) 
        {
            //DO STUFF
    }
}

public JComboBox createCombo()
{
    JComboBox box = new JComboBox();
        box.setModel(new javax.swing.DefaultComboBoxModel(new String[] 
                { "val1", "val2","val3" }));
        RulesActionListner actionL = new RulesActionListner();
        box.addItemListener(actionL);
return box;
}

and createCombo gets called multiple times but regardless of which combo box item was changed in side my ItemStateChanged method its comming from the last combo box that was created

createCombo is called at runtime, so i have a variable number of comboboxes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add separate action listeners instead of having one action listener run through if statements for each call. That section of the code will have logic that most likely has a bug that is causing the last combo box to be selected. (Maybe an else statement that should be else if, etc.).

Separating it out will be more OO and will be more flexible long term.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...