Swing JComboBox Class

Advertisements


Introduction

The class JComboBox is a component which combines a button or editable field and a drop-down list.

Class declaration

Following is the declaration for javax.swing.JComboBox class:

public class JComboBox
   extends JComponent
      implements ItemSelectable, ListDataListener, 
         ActionListener, Accessible

Field

Following are the fields for javax.swing.JList class:

  • protected String actionCommand -- 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 boolean isEditable -- 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 int maximumRowCount -- This protected field is implementation specific.

  • protected ListCellRenderer renderer -- This protected field is implementation specific.

  • protected Object selectedItemReminder -- This protected field is implementation specific.

Class constructors

S.N.Constructor & Description
1JComboBox()
Creates a JComboBox with a default data model.
2JComboBox(ComboBoxModel aModel)
Creates a JComboBox that takes its items from an existing ComboBoxModel.
3JComboBox(Object[] items)
Creates a JComboBox that contains the elements in the specified array.
4JComboBox(Vector<?> items)
Creates a JComboBox that contains the elements in the specified Vector.

Class methods

S.N.Method & Description
1void actionPerformed(ActionEvent e)
This method is public as an implementation side effect.
2protected void actionPropertyChanged(Action action, String propertyName)
Updates the combobox's state in response to property changes in associated action.
3void addActionListener(ActionListener l)
Adds an ActionListener.
4void addItem(Object anObject)
Adds an item to the item list.
5void addItemListener(ItemListener aListener)
Adds an ItemListener.
6void addPopupMenuListener(PopupMenuListener l)
Adds a PopupMenu listener which will listen to notification messages from the popup portion of the combo box.
7void configureEditor(ComboBoxEditor anEditor, Object anItem)
Initializes the editor with the specified item.
8protected void configurePropertiesFromAction(Action a)
Sets the properties on this combobox to match those in the specified Action.
9void contentsChanged(ListDataEvent e)
This method is public as an implementation side effect.
10protected PropertyChangeListener createActionPropertyChangeListener(Action a)
Creates and returns a PropertyChangeListener that is responsible for listening for changes from the specified Action and updating the appropriate properties.
11protected JComboBox.KeySelectionManager createDefaultKeySelectionManager()
Returns an instance of the default key-selection manager.
12protected void fireActionEvent()
Notifies all listeners that have registered interest for notification on this event type.
13protected void fireItemStateChanged(ItemEvent e)
Notifies all listeners that have registered interest for notification on this event type.
14void firePopupMenuCanceled()
Notifies PopupMenuListeners that the popup portion of the combo box has been canceled.
15void firePopupMenuWillBecomeInvisible()
Notifies PopupMenuListeners that the popup portion of the combo box has become invisible.
16void firePopupMenuWillBecomeVisible()
Notifies PopupMenuListeners that the popup portion of the combo box will become visible.
17AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JComboBox.
18Action getAction()
Returns the currently set Action for this ActionEvent source, or null if no Action is set.
19String getActionCommand()
Returns the action command that is included in the event sent to action listeners.
20ActionListener[] getActionListeners()
Returns an array of all the ActionListeners added to this JComboBox with addActionListener().
21ComboBoxEditor getEditor()
Returns the editor used to paint and edit the selected item in the JComboBox field.
22Object getItemAt(int index)
Returns the list item at the specified index.
23int getItemCount()
Returns the number of items in the list.
24ItemListener[] getItemListeners()
Returns an array of all the ItemListeners added to this JComboBox with addItemListener().
25JComboBox.KeySelectionManager getKeySelectionManager()
Returns the list's key-selection manager.
26int getMaximumRowCount()
Returns the maximum number of items the combo box can display without a scrollbar.
27ComboBoxModel getModel()
Returns the data model currently used by the JComboBox.
28PopupMenuListener[] getPopupMenuListeners()
Returns an array of all the PopupMenuListeners added to this JComboBox with addPopupMenuListener().
29Object getPrototypeDisplayValue()
Returns the "prototypical display" value - an Object used for the calculation of the display height and width.
30ListCellRenderer getRenderer()
Returns the renderer used to display the selected item in the JComboBox field.
31int getSelectedIndex()
Returns the first item in the list that matches the given item.
32Object getSelectedItem()
Returns the current selected item.
33Object[] getSelectedObjects()
Returns an array containing the selected item.
34ComboBoxUI getUI()
Returns the L&F object that renders this component.
35String getUIClassID()
Returns the name of the L&F class that renders this component.
36void hidePopup()
Causes the combo box to close its popup window.
37void insertItemAt(Object anObject, int index)
Inserts an item into the item list at a given index.
38protected void installAncestorListener()
39void intervalAdded(ListDataEvent e)
This method is public as an implementation side effect.
40void intervalRemoved(ListDataEvent e)
This method is public as an implementation side effect.
41boolean isEditable()
Returns true if the JComboBox is editable.
42boolean isLightWeightPopupEnabled()
Gets the value of the lightWeightPopupEnabled property.
43boolean isPopupVisible()
Determines the visibility of the popup.
44protected String paramString()
Returns a string representation of this JComboBox.
45void processKeyEvent(KeyEvent e)
Handles KeyEvents, looking for the Tab key.
46void removeActionListener(ActionListener l)
Removes an ActionListener.
47void removeAllItems()
Removes all items from the item list.
48void removeItem(Object anObject)
Removes an item from the item list.
49void removeItemAt(int anIndex)
Removes the item at anIndex This method works only if the JComboBox uses a mutable data model.
50void removeItemListener(ItemListener aListener)
Removes an ItemListener.
51void removePopupMenuListener(PopupMenuListener l)
Removes a PopupMenuListener.
52protected void selectedItemChanged()
This protected method is implementation specific.
53boolean 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.
54void setAction(Action a)
Sets the Action for the ActionEvent source.
55void setActionCommand(String aCommand)
Sets the action command that should be included in the event sent to action listeners.
56void setEditable(boolean aFlag)
Determines whether the JComboBox field is editable.
57void setEditor(ComboBoxEditor anEditor)
Sets the editor used to paint and edit the selected item in the JComboBox field.
58void setEnabled(boolean b)
Enables the combo box so that items can be selected.
59void setKeySelectionManager(JComboBox.KeySelectionManager aManager)
Sets the object that translates a keyboard character into a list selection.
60void 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.
61void setMaximumRowCount(int count)
Sets the maximum number of rows the JComboBox displays.
62void setModel(ComboBoxModel aModel)
Sets the data model that the JComboBox uses to obtain the list of items.
63void setPopupVisible(boolean v)
Sets the visibility of the popup.
64void setPrototypeDisplayValue(Object prototypeDisplayValue)
Sets the prototype display value used to calculate the size of the display for the UI portion.
65void setRenderer(ListCellRenderer aRenderer)
Sets the renderer that paints the list items and the item selected from the list in the JComboBox field.
66void setSelectedIndex(int anIndex)
Selects the item at index anIndex.
67void setSelectedItem(Object anObject)
Sets the selected item in the combo box display area to the object in the argument.
68void setUI(ComboBoxUI ui)
Sets the L&F object that renders this component.
69void showPopup()
Causes the combo box to display its popup window.
70void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JComboBox Example

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 command prompt. Go to D:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output

Swing JComboBox

Advertisements
Advertisements