Action Listener To JComboBox In Java
Chapter:
Action Listener
Last Updated:
22-09-2018 08:24:03 UTC
Program:
/* ............... START ............... */
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class JavaJComboBoxActionListner extends JFrame {
public JavaJComboBoxActionListner() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] names = new String[] { "Java", "C++", "C" };
JComboBox comboBox = new JComboBox(names);
comboBox.setEditable(true);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JComboBox comboBox = (JComboBox) event.getSource();
System.out.println("Selected Item = " + comboBox.getSelectedItem());
System.out.println("Action Command = " + event.getActionCommand());
if ("comboBoxEdited".equals(event.getActionCommand())) {
System.out.println("User has typed a string in the combo box.");
} else if ("comboBoxChanged".equals(event.getActionCommand())) {
System.out.println("User has selected an item from the combo box.");
}
}
});
getContentPane().add(comboBox);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JavaJComboBoxActionListner().setVisible(true);
}
});
}
}
/* ............... END ............... */
Output
Selected Item = C++
Action Command = comboBoxChanged
User has selected an item from the combo box.
Tags
Action Listener To JComboBox, Java, ActionListener, how to select item from combobox in java, jcombobox actionperformed, jcombobox itemlistener