devxlogo

Selecting an Item From a JComboBox…Again

Selecting an Item From a JComboBox…Again

The default behavior of the JComboBox is sufficient enough in most cases. If you select an item from the pull down list, an action event is generated and sent to any listeners that have interest in that newly selected item. However, suppose you were interested in knowing whether the same entry was chosen again–perhaps to establish settings for other fields on the screen, or even to detect a possible entry error. The JComboBox specifically prevents a new action from being invoked if the currently selected item is selected again from the pull down list. This extension of JComboBox allows new actions to be invoked, even if the same item is selected again:

 import java.util.*;import com.sun.java.swing.*;import com.sun.java.swing.event.*;import java.io.Serializable;public class AlwaysSelectableComboBox extends JComboBox implementsSerializable{    private boolean _alwaysFireOnSelect = true;    public AlwaysSelectableComboBox(ComboBoxModel aModel)  {super(aModel); }    public AlwaysSelectableComboBox(final Object items[])  {super(items); }    public AlwaysSelectableComboBox(Vector items)          {super(items); }    public AlwaysSelectableComboBox()                      { super(); }    public void setAlwaysFireOnSelect(boolean alwaysFireOnSelect)    {        _alwaysFireOnSelect = alwaysFireOnSelect;    }    public void contentsChanged(ListDataEvent e)    {        if (_alwaysFireOnSelect)        {            selectedItemReminder = null;        }        super.contentsChanged(e);    }}

The contentsChanged() method normally checks the selectedItemReminder field that holds the previously selected item. Here, we replace the selectedItemReminder with null to fake out the JComboBox into thinking that nothing had been previously selected. You may call setAlwaysFireOnSelect(false) to revert your new JComboBox extension back to the default behavior.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist