ruby student
ruby student

Reputation: 1129

JoptionPane is showed two times when a list item is selected

When I click on an item of a JComboBox to show a JoptionPane with the text of selected item , it is showed two times. How can I desactive the item listener event?

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;

public class Combo implements ItemListener {

    JFrame f;
    JComboBox cb;

    Combo() {
        f = new JFrame("Combo ex");

        String country[] = {"India", "Aus", "U.S.A", "England", "Newzeland"};

        cb = new JComboBox(country);
        cb.setBounds(50, 50, 90, 20);
        f.add(cb);
        cb.addItemListener(this);
        f.setLayout(null);
        f.setSize(400, 500);
        f.setVisible(true);

    }

    public static void main(String[] args) {
        new Combo();

    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getSource()==cb) {
            String seleccionado=(String)cb.getSelectedItem();
            JOptionPane.showMessageDialog(f, seleccionado);
        }
    }
}

Upvotes: 2

Views: 418

Answers (2)

Lightsout
Lightsout

Reputation: 3757

You want to avoid overriding itemStateChanged(). Changing the state of the item within itemStateChanged causes itemStateChanged to be fired... which is why you're seeing the dialog twice. You should use an ActionListener instead.

I slightly modified your code as an example. It should show only 1 dialog box now.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;


public class Combo{

    JFrame frame;
    JComboBox cb;

    Combo() {
        frame = new JFrame("Combo ex");

        String country[] = {"India", "Aus", "U.S.A", "England", "Newzeland"};

        cb = new JComboBox(country);
        cb.setBounds(50, 50, 90, 20);
        cb.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                String seleccionado=(String)cb.getSelectedItem();
                JOptionPane.showMessageDialog(frame, seleccionado);
            }
        });
        frame.add(cb);
        frame.setLayout(null);
        frame.setSize(400, 500);
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        new Combo();

    }

}

Upvotes: 2

user2575725
user2575725

Reputation:

Problem is, itemStateChanged() is invoked when an item has been selected or deselected by the user. In simple terms, when you select a new item, you also deselected the old item.

Try this:

if (e.getSource()==cb && e.getStateChange() == ItemEvent.SELECTED) { 
    //
}

getStateChange(), returns the type of state change (selected or deselected).

Upvotes: 1

Related Questions