How to listen Action Events from a JComboBox Component?

Sometimes we need to get the action events happening in JComboBox lets see how to capture the JComboBox action events. We can get it using getActionCommand as follows:

Whenever selected item changes action events are generated. These events are generated even if user moves through the items in displayed popup menu. Action event is generated even if the selected new item is same as old item.

// Create JComboBox
String[] menus = {"menu1", "menu2", "menu3"};
JComboBox cmbMenus = new JComboBox(menus);
// IF want to make combo box editable make setEditable as true

// Create and register listener
MenuListener menuActionListener = new MenuListener();
cmbMenus.addActionListener( menuActionListener );

class MenuListener implements ActionListener {
//Listener for listening action events whenever user moves through the ComboBox.

Object oldMenu; // For getting old menu item

public void actionPerformed(ActionEvent evt) {
JComboBox cb = (JComboBox)evt.getSource();

Object newMenu = cb.getSelectedItem();

// Determine if different from previously selected item
boolean isMenuSame = newMenu .equals(oldMenu );
oldMenu = newMenu;

if ("comboBoxEdited".equals(evt.getActionCommand())) {
// If Combobox is editable and user has typed something
} else if ("comboBoxChanged".equals(evt.getActionCommand())) {
// User selection change
// Note in action event selected item may or may not be different
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment