swing

JAVA Swing List Example

1. Introduction

JList is a swing component through which we can display the list of objects. This swing component allows user to select one or more elements. Lists can have many items, so they are often put in scroll panes. A separate model, ListModel, maintains the contents of the list. An array of objects can be easily displayed using the JList constructor that builds a read only ListModel instance automatically.
 
 

2. JAVA Swing List

2.1. Setup

This Example demonstrates how to create a List using Swing in eclipse.

Prerequisite
This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work. To learn how to install WindowBuilder tool please visit the Setup section 2.1 of the following link Setup section 2.1 of the following link click here

Create a new JAVA project lets say swing_1

  • Go to src→ right click→ New→ Other→ WindowBuilder→ select Swing Designer→ Application Window.
  • Enter the name of the application(eg. SwingListExample ) and click finish.

This will create SwingListExample.java file and will provide Source and Design tab.

2.2 Creating a List

In this example we will dynamically add and remove element to and from a list using Hire and Fire Button. To create a list a model ,i.e, ListModel is required.

A ListModel can be supplied directly to a JList by way of a constructor or the setModel method. A correct ListModel implementation notifies the set of javax.swing.event.ListDataListeners that have been added to it, each time a change occurs.

These changes are characterized by a javax.swing.event.ListDataEvent, which identifies the range of list indices that have been modified, added, or removed. JList’s ListUI is responsible for keeping the visual representation up to date with changes, by listening to the model. DefaultListModel class is used to maintain list elements by JList applications. This class implements the ListModel interface and also provides a java.util.Vector like API.

Applications that need a more custom ListModel implementation may instead wish to subclass AbstractListModel, which provides basic support for managing and notifying listeners.

2.3. Creating a Model

There are three ways to create a list model:

  • DefaultListModel — everything is pretty much taken care of for you. The examples in this page use DefaultListModel.
  • AbstractListModel — you manage the data and invoke the “fire” methods. For this approach, you must subclass AbstractListModel and implement the getSize and getElementAt methods inherited from the ListModel interface.
  • ListModel — you manage everything

2.4. Initializing a list

SwingListExample.java

        listModel = new DefaultListModel();
        listModel.addElement("Jasmine Mehra");
        listModel.addElement("Ankit Mishra");
        listModel.addElement("Madhuri Sanghvi");
        listModel.addElement("Alok Kumar");
        listModel.addElement("Rohit Bothra");
        listModel.addElement("Rahul Aggarwal");
        
 
        //Create the list and put it in a scroll pane.
        list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setSelectedIndex(0);
        list.addListSelectionListener(this);
        list.setVisibleRowCount(5);
        JScrollPane listScrollPane = new JScrollPane(list);

The above code creates and sets up the list. The code passes an array to the list’s constructor. The array is filled with strings. In our example, the strings happen to be person’s names.

Other JList constructors let you initialize a list from a Vector or from an object that adheres to the ListModel interface. If you initialize a list with an array or vector, the constructor implicitly creates a default list model. The default list model is immutable — you cannot add, remove, or replace items in the list. To create a list whose items can be changed individually, set the list’s model to an instance of a mutable list model class, such as an instance of DefaultListModel. You can set a list’s model when you create the list or by calling the setModel method.

setSelectionMode specifies how many items the user can select, and whether they must be contiguous.
setLayoutOrientation lets the list display its data in multiple columns. The possible value such as, JList.HORIZONTAL_WRAP demonstrates that the list should display its items from left to right before wrapping to a new row. Another value that can be used is JList.VERTICAL_WRAP , which specifies that the data be displayed from top to bottom before wrapping to a new column.

setVisibleRowCount(-1) makes the list display the maximum number of items possible in the available space onscreen. Another popular use of setVisibleRowCount is to specify to the lists’s scroll pane how many rows the list prefers to display.

2.5. Selecting Items in a List

A list uses an instance of ListSelectionModel to manage its selection. By default, a list selection model allows any combination of items to be selected at a time. You can specify a different selection mode by calling the setSelectionMode method on the list. For example, SwingListExample set the selection mode to SINGLE_SELECTION (a constant defined by ListSelectionModel) so that only one item in the list can be selected. The three list selection modes are described below:

  • SINGLE_SELECTION : Only one item can be selected at a time. When the user selects an item, any previously selected item is deselected first.
  • SINGLE_INTERVAL_SELECTION: Multiple, contiguous items can be selected. When the user begins a new selection range, any previously selected items are deselected first.
  • MULTIPLE_INTERVAL_SELECTION : The default. Any combination of items can be selected. The user must explicitly deselect items.

3. Change in Values

No matter which selection mode your list uses, the list fires list selection events whenever the selection changes. You can process these events by adding a list selection listener to the list with the addListSelectionListener method. A list selection listener must implement one method: valueChanged . Here is the valueChanged method for the listener in SwingListExample.

SwingListExample.java

 //This method is required by ListSelectionListener.
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() == false) {
 
            if (list.getSelectedIndex() == -1) {
            //No selection, disable fire button.
                fireButton.setEnabled(false);
 
            } else {
            //Selection, enable the fire button.
                fireButton.setEnabled(true);
            }
        }
    }

3.1 Adding and removing items to and from a List

The SwingListExample example creates a list whose contents can change. Here is the SwingListExample code that creates a mutable list model object, puts the initial items in it, and uses the list model to create a list:

SwingListExample.java

 

  listModel = new DefaultListModel();
        listModel.addElement("Jasmine Mehra");
        listModel.addElement("Ankit Mishra");
        listModel.addElement("Madhuri Sanghvi");
        listModel.addElement("Alok Kumar");
        listModel.addElement("Rohit Bothra");
        listModel.addElement("Rahul Aggarwal");
 
        //Create the list and put it in a scroll pane.
        list = new JList(listModel);

This example uses an instance of DefaultListModel, a class provided by Swing. To create a DefaulLIstModel a program needs to explicitly mention it. If your requirement is not met through DefaultListModel then you can write a custom list model, which must adhere to the ListModel interface.

Here is the actionPerformed method for the action listener shared by the Hire button and the text field:

SwingListExample.java

 

   public void actionPerformed(ActionEvent e) {
            String name = employeeName.getText();
 
            //User didn't type in a unique name...
            if (name.equals("") || alreadyInList(name)) {
                Toolkit.getDefaultToolkit().beep();
                employeeName.requestFocusInWindow();
                employeeName.selectAll();
                return;
            }
 
            int index = list.getSelectedIndex(); //get selected index
            if (index == -1) { //no selection, so insert at beginning
                index = 0;
            } else {           //add after the selected item
                index++;
            }
 
            listModel.insertElementAt(employeeName.getText(), index);
            //If we just wanted to add to the end, we'd do this:
            //listModel.addElement(employeeName.getText());
 
            //Reset the text field.
            employeeName.requestFocusInWindow();
            employeeName.setText("");
 
            //Select the new item and make it visible.
            list.setSelectedIndex(index);
            list.ensureIndexIsVisible(index);
        }

This code uses the list model’s insertElementAt method to insert the new name after the current selection or, if no selection exists, at the beginning of the list. If you just wish to add to the end of the list, you can use DefaultListModel’s addElement method instead.
Whenever items are added to, removed from, or modified in a list, the list model fires list data events.

The following code snippet shows the actionPerformed method for the action listener registered on the Fire button. removes method is used to remove the selected item from the list. Fire button is disabled if the list is empty.

SwingListExample.java

 

 public void actionPerformed(ActionEvent e) {
            //This method can be called only if
            //there's a valid selection
            //so go ahead and remove whatever's selected.
            int index = list.getSelectedIndex();
            listModel.remove(index);
 
            int size = listModel.getSize();
 
            if (size == 0) { //Nobody's left, disable firing.
                fireButton.setEnabled(false);
 
            } else { //Select an index.
                if (index == listModel.getSize()) {
                    //removed item in last position
                    index--;
                }
 
                list.setSelectedIndex(index);
                list.ensureIndexIsVisible(index);
            }
        }

3.2 List API

The following tables list the commonly used JList constructors and methods. Much of the operation of a list is managed by other objects. The items in the list are managed by a list model object, the selection is managed by a list selection model object, and most programs put a list in a scroll panel to handle scrolling.

The API for using lists falls into these categories:

3.2.1 Initializing List Data

  • JList(ListModel),JList(Object[]),JList(Vector)JList(): Create a list with the initial list items specified. The second and third constructors implicitly create an immutable ListModel you should not subsequently modify the passed-in array or Vector.
  • void setModel(ListModel),ListModel getModel(): Set or get the model that contains the contents of the list.
  • void setListData(Object[]),void setListData(Vector): Set the items in the list. These methods implicitly create an immutable ListModel.

3.2.2 Displaying the List

  • void setVisibleRowCount(int),int getVisibleRowCount(): Set or get the visibleRowCount property. For a VERTICAL layout orientation, this sets or gets the preferred number of rows to display without requiring scrolling. For the HORIZONTAL_WRAP or VERTICAL_WRAP layout orientations, it defines how the cells wrap. See the setLayoutOrientation(int) for more information. The default value of this property is VERTICAL.
  • void setLayoutOrientation(int),int getLayoutOrientation(): Set or get the way list cells are laid out. The possible layout formats are specified by the JList-defined values VERTICAL (a single column of cells; the default), HORIZONTAL_WRAP (“newspaper” style with the content flowing horizontally then vertically), and VERTICAL_WRAP (“newspaper” style with the content flowing vertically then horizontally).
  • int getFirstVisibleIndex(),int getLastVisibleIndex(): Get the index of the first or last visible item.
  • void ensureIndexIsVisible(int): Scroll so that the specified index is visible within the viewport that this list is in.

Similarly, there are methods and constructors for other 2 categories too.

  • Managing the List’s Selection
  • Managing List Data

4. Code & Output

The upper sections described how an item can be added or removed to or from the list at the runtime.
In this example we have created 2 buttons Hire and Fire. Hire adds an element at runtime at a specified position whereas, Fire removes an element from the specified position.

After execution of code output will look like the one below.

JAVA Swing List
JAVA Swing List

If you enter a text in the textbox it will enable the Hire button and output will look like the one below.

JAVA Swing List
JAVA Swing List

5. Download

This was an example of creation of swing JAVA List.

Download
You can download the full source code of this example here: SwingListExample

Jyoti Jha

Jyoti is a tech enthusiast and is an avid programmer. She holds a post graduation degree in (M.Tech) Computer Science Engineering from Thapar Univeristy, Patiala, India. Post her graduate studies, she has worked in Software companies such as SLK Software and Aricent, India as Software Engineer in various projects primarily in the field of Requirement analysis and design, implementing new algorithms in C++ and JAVA used in ISDN network and designing databases and. She is inquisitive about socio economic reforms as well as advancement in technical fronts and keep herself informed with TED talks and various blogs.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button