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.
Action Listener To JComboBox In Java

Tags

Action Listener To JComboBox, Java, ActionListener, how to select item from combobox in java, jcombobox actionperformed, jcombobox itemlistener

Similar Programs Chapter Last Updated
Add Action Listener To JTextField In Java Action Listener 08-08-2016
Get Event Source From ActionEvent Swing Java Action Listener 08-08-2016
ActionListener And Action Class Level Variable Swing Event Action Listener 08-08-2016
ActionListener Inner Class To Handle Event In Java Action Listener 28-07-2016
ActionListener Event Source In Java ActionPerformed Method Action Listener 28-07-2016
ActionListener Handling An Action In Java Action Listener 28-07-2016

1