Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...