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);
}
}
}
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();
}
}