ListSelectionListener & ItemListener
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class StatusChange extends JFrame {
public StatusChange() {
getContentPane().setLayout(new FlowLayout());
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
model.addElement("one");
model.addElement("two");
model.addElement("three");
model.addElement("four");
model.addElement("five");
model.addElement("six");
model.addElement("seven");
model.addElement("eight");
model.addElement("nine");
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
JList list = (JList) e.getSource();
// execute twice
System.out.printf("=====%s=====%n", list.getSelectedValue());
if (list.getValueIsAdjusting()) {
// execute once
System.out.println(list.getSelectedValue());
}
}
});
getContentPane().add(new JScrollPane(list));
JComboBox combo = new JComboBox();
combo.addItem("one");
combo.addItem("two");
combo.addItem("three");
combo.addItem("four");
combo.addItem("five");
combo.addItem("six");
combo.addItem("seven");
combo.addItem("eight");
combo.addItem("nine");
combo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
JComboBox combo = (JComboBox) e.getSource();
// execute twice (occurs on selected & deselected)
System.out.printf("-----%s-----%n", combo.getSelectedItem());
if (e.getStateChange() == e.SELECTED) {
// execute once
System.out.println(combo.getSelectedItem());
}
}
});
getContentPane().add(combo);
pack();
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screen.width - this.getWidth()) / 2, (screen.height - this.getHeight()) / 2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new StatusChange();
}
}