The Java Developers Almanac 1.4


Order this book from Amazon.

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

e778. Adding and Removing an Item in a JList Component

The default model for a list does not allow the addition and removal of items. The list must be created with a DefaultListModel.
    // Create a list that allows adds and removes
    DefaultListModel model = new DefaultListModel();
    JList list = new JList(model);
    
    // Initialize the list with items
    String[] items = {"A", "B", "C", "D"};
    for (int i=0; i<items.length; i++) {
        model.add(i, items[i]);
    }
    
    // Append an item
    int pos = list.getModel().getSize();
    model.add(pos, "E");
    
    // Insert an item at the beginning
    pos = 0;
    model.add(pos, "a");
This method replaces an item:
    
    // Replace the 2nd item
    pos = 1;
    model.set(pos, "b");
These methods are used to remove items:
    
    // Remove the first item
    pos = 0;
    model.remove(pos);
    
    // Remove the last item
    pos = model.getSize()-1;
    if (pos >= 0) {
        model.remove(pos);
    }
    
    // Remove all items
    model.clear();

 Related Examples
e774. Creating a JList Component
e775. Setting the Dimensions of an Item in a JList Component
e776. Setting a Tool Tip for an Item in a JList Component
e777. Getting the Items in a JList Component
e779. Getting the Selected Items in a JList Component
e780. Setting the Selected Items in a JList Component
e781. Setting the Selection Mode of a JList Component
e782. Arranging Items in a JList Component
e783. Detecting Double and Triple Clicks on an Item in a JList Component
e784. Listening for Changes to the Selection in a JList Component
e785. Listening for Changes to the Items in a JList Component

See also: Actions    JButton    JCheckBox    JComboBox    JDesktop and JInternalFrame    JFrame, JWindow, JDialog    JLabel    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.