This example demonstrates the ItemListener
to listen for changes to the selected item in the JComboBox
component.
package org.kodejava.swing;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.event.ItemEvent;
import java.awt.*;
public class ComboBoxSelectionChange extends JFrame {
public ComboBoxSelectionChange() {
initialize();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new ComboBoxSelectionChange().setVisible(true));
}
private void initialize() {
setSize(300, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
String[] items = new String[]{"A", "B", "C", "D", "E", "F"};
JComboBox<String> comboBox = new JComboBox<>(items);
final JTextArea textArea = new JTextArea(5, 15);
textArea.setBorder(new BevelBorder(BevelBorder.LOWERED));
// For listening to the changes of the selected items in the combo box
// we need to add an ItemListener to the combo box component as shown
// below.
// Listening if a new items of the combo box has been selected.
comboBox.addItemListener(event -> {
// The item affected by the event.
String item = (String) event.getItem();
textArea.append("Affected items: " + item + "\n");
if (event.getStateChange() == ItemEvent.SELECTED) {
textArea.append(item + " selected\n");
}
if (event.getStateChange() == ItemEvent.DESELECTED) {
textArea.append(item + " deselected\n");
}
});
getContentPane().add(comboBox);
getContentPane().add(textArea);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024