Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Mar 4, 1999

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 implements
Serializable
{
    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.
Roy Lachapelle
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date