Question

I am new to Java and Swing and am following zetcode tutorial. I want to add multiple JComboBoxes and store the index selected for each one of those. index1 should hold selected index from 1st instance of JComboBox and index2 should hold selected index from 2nd instance of JComboBox. For one JComboBox it can be done like this:

public ComboBox() {

    setLayout(new BoxLayout(getContentPane(), 
    BoxLayout.Y_AXIS));
    add(Box.createRigidArea(new Dimension(0, 35)));

    combobox = new JComboBox(authors);
    combobox.addItemListener(this);
    add(combobox);
}
public void itemStateChanged(ItemEvent e) {

    if (e.getStateChange() == ItemEvent.SELECTED) {
        JComboBox combo = (JComboBox) e.getSource();
        int index = combo.getSelectedIndex();
        display.setIcon(new ImageIcon(
            ClassLoader.getSystemResource(images[index])));
    }

}

So if I could write the name of itemlistener that should be called for each JComboBox and then instead of writing combobox.addItemListener(this), I could write combobox.addItemListener(itemListener1). How do I do this?

Was it helpful?

Solution

try doing like this

combobox1.addItemListener(this);
combobox2.addItemListener(this);
..
comboboxn.addItemListener(this);

public void actionPerformed(ActionEvent e) {
 if(e.getSource().equals(comboBox1))
 {
  \\do something
 }
 else if(e.getSource().equals(comboBox2))
 {
  \\do something
 }
..
 else if(e.getSource().equals(comboBoxn))
 {
  \\do something
 }

OTHER TIPS

Use inner or anonymous classes, it helps to avoid 'if - else' statements.

Exemple! of anonymous class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top