SWING - JComboBox Class

The class JComboBox is a component which combines a button or editable field and a drop-down list.
Following is the declaration for javax.swing.JComboBox class −
public class JComboBox
   extends JComponent
      implements ItemSelectable, ListDataListener, ActionListener, Accessible

Following are the fields for javax.swing.JList class −
protected String actionCommand − This protected field is implementation specific.
protected String actionCommand − This protected field is implementation specific.
protected ComboBoxModel dataModel − This protected field is implementation specific.
protected ComboBoxModel dataModel − This protected field is implementation specific.
protected ComboBoxEditor editor − This protected field is implementation specific.
protected ComboBoxEditor editor − This protected field is implementation specific.
protected boolean isEditable − This protected field is implementation specific.
protected boolean isEditable − This protected field is implementation specific.
protected JComboBox.KeySelectionManager keySelectionManager − This protected field is implementation specific.
protected JComboBox.KeySelectionManager keySelectionManager − This protected field is implementation specific.
protected boolean lightWeightPopupEnabled − This protected field is implementation specific.
protected boolean lightWeightPopupEnabled − This protected field is implementation specific.
protected int maximumRowCount − This protected field is implementation specific.
protected int maximumRowCount − This protected field is implementation specific.
protected ListCellRenderer renderer − This protected field is implementation specific.
protected ListCellRenderer renderer − This protected field is implementation specific.
protected Object selectedItemReminder − This protected field is implementation specific.
protected Object selectedItemReminder − This protected field is implementation specific.
JComboBox()
Creates a JComboBox with a default data model.
JComboBox(ComboBoxModel aModel)
Creates a JComboBox that takes its items from an existing ComboBoxModel.
JComboBox(Object[] items)
Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items)
Creates a JComboBox that contains the elements in the specified Vector.
void actionPerformed(ActionEvent e)
This method is public as an implementation side effect.
protected void actionPropertyChanged(Action action, String propertyName)
Updates the ComboBox's state in response to property changes in associated action.
void addActionListener(ActionListener l)
Adds an ActionListener.
void addItem(Object anObject)
Adds an item to the item list.
void addItemListener(ItemListener aListener)
Adds an ItemListener.
void addPopupMenuListener(PopupMenuListener l)
Adds a PopupMenu listener which will listen to notification messages from the popup portion of the ComboBox.
void configureEditor(ComboBoxEditor anEditor, Object anItem)
Initializes the editor with the specified item.
protected void configurePropertiesFromAction(Action a)
Sets the properties on this ComboBox to match those in the specified Action.
void contentsChanged(ListDataEvent e)
This method is public as an implementation side effect.
protected PropertyChangeListener	createActionPropertyChangeListener(Action a)
Creates and returns a PropertyChangeListener responsible for listening to changes from the specified Action and updating the appropriate properties.
protected JComboBox.KeySelectionManager createDefaultKeySelectionManager()
Returns an instance of the default key-selection manager.
protected void fireActionEvent()
Notifies all listeners who have registered interest for notification on this event type.
protected void fireItemStateChanged(ItemEvent e)
Notifies all listeners who have registered interest for notification on this event type.
void firePopupMenuCanceled()
Notifies PopupMenuListeners that the popup portion of the ComboBox has been canceled.
void firePopupMenuWillBecomeInvisible()
Notifies PopupMenuListeners that the popup portion of the ComboBox has become invisible.
void firePopupMenuWillBecomeVisible()
Notifies PopupMenuListeners that the popup portion of the ComboBox will become visible.
AccessibleContext	getAccessibleContext()
Gets the AccessibleContext associated with this JComboBox.
Action getAction()
Returns the currently set Action for this ActionEvent source, or null if no Action is set.
String getActionCommand()
Returns the action command that is included in the event sent to action listeners.
ActionListener[] getActionListeners()
Returns an array of all the ActionListeners added to this JComboBox with addActionListener().
ComboBoxEditor getEditor()
Returns the editor used to paint and edit the selected item in the JComboBox field.
Object getItemAt(int index)
Returns the list item at the specified index.
int getItemCount()
Returns the number of items in the list.
ItemListener[] getItemListeners()
Returns an array of all the ItemListeners added to this JComboBox with addItemListener().
JComboBox.KeySelectionManager getKeySelectionManager()
Returns the list's key-selection manager.
int getMaximumRowCount()
Returns the maximum number of items the combo box can display without a scrollbar.
ComboBoxMode getModel()
Returns the data model currently used by the JComboBox.
PopupMenuListener[]getPopupMenuListeners()
Returns an array of all the PopupMenuListeners added to this JComboBox with addPopupMenuListener().
Object getPrototypeDisplayValue()
Returns the "prototypical display" value - an Object used for the calculation of the display height and width.
ListCellRenderer	getRenderer()
Returns the renderer used to display the selected item in the JComboBox field.
int getSelectedIndex()
Returns the first item in the list that matches the given item.
Object getSelectedItem()
Returns the current selected item.
Object[] getSelectedObjects()
Returns an array containing the selected item.
ComboBoxUI getUI()
Returns the L&F object that renders this component.
String getUIClassID()
Returns the name of the L&F class that renders this component.
void hidePopup()
Causes the ComboBox to close its popup window.
void insertItemAt(Object anObject, int index)
Inserts an item into the item list at a given index.
protected void installAncestorListener()
void intervalAdded(ListDataEvent e)
This method is public as an implementation side effect.
void intervalRemoved(ListDataEvent e)
This method is public as an implementation side effect.
boolean isEditable()
Returns true if the JComboBox is editable.
boolean isLightWeightPopupEnabled()
Gets the value of the lightWeightPopupEnabled property.
boolean isPopupVisible()
Determines the visibility of the popup.
protected String	paramString()
Returns a string representation of this JComboBox.
void processKeyEvent(KeyEvent e)
Handles KeyEvents, looking for the Tab key.
void removeActionListener(ActionListener l)
Removes an ActionListener.
void removeAllItems()
Removes all items from the item list.
void removeItem(Object anObject)
Removes an item from the item list.
void removeItemAt(int anIndex)
Removes the item at anIndex This method works only if the JComboBox uses a mutable data model.
void removeItemListener(ItemListener aListener)
Removes an ItemListener.
void removePopupMenuListener(PopupMenuListener l)
Removes a PopupMenuListener.
protected void selectedItemChanged()
This protected method is implementation specific.
boolean selectWithKeyChar(char keyChar)
Selects the list item that corresponds to the specified keyboard character and returns true, if there is an item corresponding to that character.
void setAction(Action a)
Sets the Action for the ActionEvent source.
void setActionCommand(String aCommand)
Sets the action command that should be included in the event sent to action listeners.
void setEditable(boolean aFlag)
Determines whether the JComboBox field is editable.
void setEditor(ComboBoxEditor anEditor)
Sets the editor used to paint and edit the selected item in the JComboBox field.
void setEnabled(boolean b)
Enables the ComboBox so that items can be selected.
void setKeySelectionManager(JComboBox.KeySelectionManager aManager)
Sets the object translates a keyboard character into a list selection.
void setLightWeightPopupEnabled(boolean aFlag)
Sets the lightWeightPopupEnabled property, which provides a hint as to whether or not a lightweight Component should be used to contain the JComboBox, versus a heavyweight Component such as a Panel or a Window.
void setMaximumRowCount(int count)
Sets the maximum number of rows the JComboBox displays.
void setModel(ComboBoxModel aModel)
Sets the data model that the JComboBox uses to obtain the list of items.
void setPopupVisible(boolean v)
Sets the visibility of the popup.
void setPrototypeDisplayValue(Object prototypeDisplayValue)
Sets the prototype display value used to calculate the size of the display for the UI portion.
void setRenderer(ListCellRenderer aRenderer)
Sets the renderer that paints the list items and the item selected from the list in the JComboBox field.
void setSelectedIndex(int anIndex)
Selects the item at index anIndex.
void setSelectedItem(Object anObject)
Sets the selected item in the ComboBox display area to the object in the argument.
void setUI(ComboBoxUI ui)
Sets the L&F object that renders this component.
void showPopup()
Causes the ComboBox to display its popup window.
void updateUI()
Resets the UI property to a value from the current look and feel.
This class inherits methods from the following classes −
javax.swing.JComponent
java.awt.Container
java.awt.Component
java.lang.Object
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;

   public SwingControlDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showComboboxDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    
      statusLabel.setSize(350,100);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showComboboxDemo(){                                    
      headerLabel.setText("Control in action: JComboBox"); 
      final DefaultComboBoxModel fruitsName = new DefaultComboBoxModel();

      fruitsName.addElement("Apple");
      fruitsName.addElement("Grapes");
      fruitsName.addElement("Mango");
      fruitsName.addElement("Peer");

      final JComboBox fruitCombo = new JComboBox(fruitsName);    
      fruitCombo.setSelectedIndex(0);

      JScrollPane fruitListScrollPane = new JScrollPane(fruitCombo);    
      JButton showButton = new JButton("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) { 
            String data = "";
            if (fruitCombo.getSelectedIndex() != -1) {                     
               data = "Fruits Selected: " 
                  + fruitCombo.getItemAt
                  (fruitCombo.getSelectedIndex());             
            }              
            statusLabel.setText(data);
         }
      }); 
      controlPanel.add(fruitListScrollPane);          
      controlPanel.add(showButton);    
      mainFrame.setVisible(true);             
   }
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output.

    30 Lectures 
     3.5 hours 

 Pranjal Srivastava

    13 Lectures 
     1 hours 

 Pranjal Srivastava

    25 Lectures 
     4.5 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    14 Lectures 
     1.5 hours 

 Travis Rose

    14 Lectures 
     1 hours 

 Travis Rose
 Print
 Add Notes
 Bookmark this page