The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing  [141 examples] > JComboBox  [12 examples]

e759. Adding and Removing an Item in a JComboBox Component

There is no method for replacing an item. To replace an item, first remove the item and then insert the new one.
    // Create a read-only combobox; the combobox is read-only
    // in that it does not allow the user to type in a new item.
    // The combobox still allows programmatic changes to its items.
    String[] items = {"item1", "item2"};
    JComboBox cb = new JComboBox(items);
    
    // Add an item to the start of the list
    cb.insertItemAt("item0", 0);
    
    // Add an item after the first item
    cb.insertItemAt("item0.5", 1);
    
    // Add an item to the end of the list
    cb.addItem("item3");
    
    // Remove first item
    cb.removeItemAt(0);
    
    // Remove the last item
    cb.removeItemAt(cb.getItemCount()-1);
    
    // Remove all items
    cb.removeAllItems();

 Related Examples
e756. Creating a JComboBox Component
e757. Getting and Setting the Selected Item in a JComboBox Component
e758. Getting the Items in a JComboBox Component
e760. Selecting an Item in a JComboBox Component with Multiple Keystrokes
e761. Determining If the Menu of a JComboBox Component Is Visible
e762. Displaying the Menu in a JComboBox Component Using a Keystroke
e763. Displaying the Menu in a JComboBox Component Using a Keystroke If the Selected Item Is Not Unique
e764. Setting the Number of Visible Items in the Menu of a JComboBox Component
e765. Listening for Changes to the Selected Item in a JComboBox Component
e766. Listening for Action Events from a JComboBox Component
e767. Determining When the Menu of a JComboBox Component Is Displayed

See also: Actions    JButton    JCheckBox    JDesktop and JInternalFrame    JFrame, JWindow, JDialog    JLabel    JList    JProgressBar    JRadioButton    JScrollPane    JSlider    JSpinner    JSplitPane    JTabbedPane    JToolBar    Keystrokes and Input Maps    Layout    Look and Feel    Menus    Progress Monitor    The Screen    Tool Tips    UI Default Values   


© 2002 Addison-Wesley.