1

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.

user650608
  • 11
  • 1
  • 1
  • 4
  • What do you mean by "problem is when I change something". Is it a GUI change (selection) or programmatic change (through model). – Snicolas Jun 30 '11 at 18:27
  • to reduce listening all event add to your "itemStateChanged()" this codeline "if (e.getStateChange() == ItemEvent.SELECTED) {}" – mKorbel Jun 30 '11 at 19:00
  • No one seems to find, please post the whole code. I would like to be able to compile it and test. – Snicolas Jun 30 '11 at 20:10

3 Answers3

2

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.

jzd
  • 23,473
  • 9
  • 54
  • 76
2

@user650608 your questions isn't clear for me, do you mean - going this way, or am I wrong ?,

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ComboBoxTwo extends JFrame implements ActionListener, ItemListener {

    private static final long serialVersionUID = 1L;
    private JComboBox mainComboBox;
    private JComboBox subComboBox;
    private Hashtable<Object, Object> subItems = new Hashtable<Object, Object>();

    public ComboBoxTwo() {
        String[] items = {"Select Item", "Color", "Shape", "Fruit", "Size"};
        mainComboBox = new JComboBox(items);
        mainComboBox.addActionListener(this);
        mainComboBox.addItemListener(this);
        //prevent action events from being fired when the up/down arrow keys are used
        //mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
        getContentPane().add(mainComboBox, BorderLayout.WEST);
        subComboBox = new JComboBox();//  Create sub combo box with multiple models
        subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
        subComboBox.addItemListener(this);
        getContentPane().add(subComboBox, BorderLayout.CENTER);
        String[] subItems1 = {"Select Color", "Red", "Blue", "Green"};
        subItems.put(items[1], subItems1);
        String[] subItems2 = {"Select Shape", "Circle", "Square", "Triangle"};
        subItems.put(items[2], subItems2);
        String[] subItems3 = {"Select Fruit", "Apple", "Orange", "Banana"};
        subItems.put(items[3], subItems3);
        String[] subItems4 = {"Select Size", "Big", "Middle", "Small"};
        subItems.put(items[4], subItems4);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String item = (String) mainComboBox.getSelectedItem();
        Object o = subItems.get(item);
        if (o == null) {
            subComboBox.setModel(new DefaultComboBoxModel());
        } else {
            subComboBox.setModel(new DefaultComboBoxModel((String[]) o));
        }
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            if (e.getSource() == mainComboBox) {
                if (mainComboBox.getSelectedIndex() != 0) {
                    FirstDialog firstDialog = new FirstDialog(ComboBoxTwo.this,
                            mainComboBox.getSelectedItem().toString(), "Please wait,  Searching for ..... ");
                }
            } 
        }
    }

    private class FirstDialog extends JDialog {

        private static final long serialVersionUID = 1L;

        FirstDialog(final Frame parent, String winTitle, String msgString) {
            super(parent, winTitle);
            setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
            JLabel myLabel = new JLabel(msgString);
            JButton bNext = new JButton("Stop Processes");
            add(myLabel, BorderLayout.CENTER);
            add(bNext, BorderLayout.SOUTH);
            bNext.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent evt) {
                    setVisible(false);
                }
            });
            javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                }
            });
            t.setRepeats(false);
            t.start();
            setLocationRelativeTo(parent);
            setSize(new Dimension(400, 100));
            setVisible(true);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new ComboBoxTwo();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

Did you try using an ItemListener instead ?

The doc says an ActionEvent is fired every time the combo box is edited.

Regards, Stéphane

Snicolas
  • 37,840
  • 15
  • 114
  • 173
  • @little bunny foo foo that's not true, that not correct Listener for JComboBox (my view), @Snicolas +1 – mKorbel Jun 30 '11 at 18:28
  • @mKorbel, what are you talking about? – mre Jun 30 '11 at 18:43
  • @little bunny foo foo , nothing complicated, if Item changed and action has direrction change JComboBox itself, then ActionListener is correct decision, for output to the GUI from JComboBox is better ItemListener :-), I know that official tutorial on sn-Oracle pages ... – mKorbel Jun 30 '11 at 18:47
  • @mKorbel, Alright? All I was saying is that the suggestion to register an `ItemListener` instead will not make a difference in this particular case. I'm not sure who you're preaching to... – mre Jun 30 '11 at 18:48
  • @little bunny foo foo 'I'm not sure who you're preaching to...' nothing against your person, my respect ... – mKorbel Jun 30 '11 at 18:55
  • @mKorbel, I wasn't preaching to anyone. I was asking @Snicolas why she thought using an `ItemListener` would resolve OP's problem. All of a sudden, you started going on a rant as if I had actually said something else entirely. Make sure you know who said what...I really think you have me confused with someone else. – mre Jun 30 '11 at 18:57
  • @little bunny foo foo, please ceasefire see my post – mKorbel Jun 30 '11 at 19:30