The code below shows you how to add an ActionListener
to a JComboBox
component. In the snippet we add a listener by calling the addActionListener()
method and give an instance of ActionListener
listener as an anonymous class (a class without a specified name) as the parameter.
The ActionListener
interface contract said that we must implement the actionPerformed(ActionEvent e)
method. This is the place where the event will be handled by our program.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.FlowLayout;
public class ComboBoxActionListener extends JFrame {
public ComboBoxActionListener() {
initialize();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new ComboBoxActionListener().setVisible(true));
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
String[] names = new String[]{
"John", "Paul", "George", "Ringo"
};
JComboBox<String> comboBox = new JComboBox<>(names);
comboBox.setEditable(true);
// Create an ActionListener for the JComboBox component.
comboBox.addActionListener(event -> {
// Get the source of the component, which is our combo
// box.
JComboBox comboBox1 = (JComboBox) event.getSource();
// Print the selected items and the action command.
Object selected = comboBox1.getSelectedItem();
System.out.println("Selected Item = " + selected);
String command = event.getActionCommand();
System.out.println("Action Command = " + command);
// Detect whether the action command is "comboBoxEdited"
// or "comboBoxChanged"
if ("comboBoxEdited".equals(command)) {
System.out.println("User has typed a string in " +
"the combo box.");
} else if ("comboBoxChanged".equals(command)) {
System.out.println("User has selected an item " +
"from the combo box.");
}
});
getContentPane().add(comboBox);
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023