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 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