Using JList in Java Swing tutorial

JList is a Swing component in Java that allows users to display and select a list of items. It can be used for selecting one or multiple items from a predefined list of values.

JList is commonly used for creating forms, selection menus, and more interactive graphical interfaces.

In this tutorial, we will explore:

1. Creating a Basic JList

The simplest way to create a JList is by using the constructor that takes an array or vector of items.

Example 1: Basic JList

import javax.swing.*;

public class JListExample1 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Basic JList Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 200);

            // Create a list of items
            String[] items = {"Apple", "Banana", "Orange", "Grapes"};

            // Create a JList with the items
            JList list = new JList<>(items);

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(list);
            frame.setVisible(true);
        });
    }
}

Explanation:

A JList is created with a list of items (“Apple”, “Banana”, “Orange”, and “Grapes”).
The JList is added to a JFrame and displayed in the user interface.

2. Handling Item Selection Events

You can handle selection events in a JList by adding a ListSelectionListener. This allows you to perform actions when the user selects an item from the list.

Example 2: Handling Item Selection

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class JListExample2 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Item Selection Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 200);

            String[] items = {"Red", "Green", "Blue", "Yellow"};
            JList list = new JList<>(items);
            JLabel label = new JLabel("Selected Color: ");

            // Add a ListSelectionListener to handle item selection
            list.addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (!e.getValueIsAdjusting()) {
                        String selectedItem = list.getSelectedValue();
                        label.setText("Selected Color: " + selectedItem);
                    }
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(new JScrollPane(list));  // Add the list with a scroll pane
            frame.add(label);
            frame.setVisible(true);
        });
    }
}

Explanation:

A ListSelectionListener is added to the JList to listen for changes in the selected item.
When the user selects an item, the valueChanged() method is called, and the selected value is retrieved using getSelectedValue().
The label is updated to display the selected color.

3. Enabling Multiple Selection in JList

By default, JList only allows single selection. However, you can enable multiple selection modes, such as allowing the user to select multiple items at once.

Example 3: Multiple Selection in JList

import javax.swing.*;
import java.util.List;

public class JListExample3 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Multiple Selection Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 200);

            String[] items = {"Apple", "Banana", "Orange", "Grapes", "Pineapple"};
            JList list = new JList<>(items);
            list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); // Enable multiple selection

            JButton button = new JButton("Show Selected Items");
            JLabel label = new JLabel("Selected items will appear here");

            // Show selected items when button is clicked
            button.addActionListener(e -> {
                List selectedItems = list.getSelectedValuesList();
                label.setText("Selected: " + selectedItems.toString());
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(new JScrollPane(list)); // Add the list with a scroll pane
            frame.add(button);
            frame.add(label);
            frame.setVisible(true);
        });
    }
}

Explanation:

The setSelectionMode() method is used to enable multiple selection. We use ListSelectionModel.MULTIPLE_INTERVAL_SELECTION to allow the user to select multiple items.
When the button is clicked, the selected items are retrieved using getSelectedValuesList() and displayed in the label.

4. Adding and Removing Items Dynamically

You can add and remove items from the JList dynamically at runtime by working with its DefaultListModel.

Example 4: Adding and Removing Items Dynamically

import javax.swing.*;

public class JListExample4 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Add/Remove Items Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 200);

            DefaultListModel listModel = new DefaultListModel<>();
            listModel.addElement("Apple");
            listModel.addElement("Banana");

            JList list = new JList<>(listModel);
            JTextField newItemField = new JTextField(10);
            JButton addButton = new JButton("Add Item");
            JButton removeButton = new JButton("Remove Selected");

            // Add an item to the list when the button is clicked
            addButton.addActionListener(e -> {
                String newItem = newItemField.getText();
                if (!newItem.isEmpty()) {
                    listModel.addElement(newItem); // Add the new item
                    newItemField.setText(""); // Clear the input field
                }
            });

            // Remove the selected item from the list
            removeButton.addActionListener(e -> {
                String selectedItem = list.getSelectedValue();
                if (selectedItem != null) {
                    listModel.removeElement(selectedItem); // Remove the selected item
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(new JScrollPane(list)); // Add the list with a scroll pane
            frame.add(newItemField);
            frame.add(addButton);
            frame.add(removeButton);

            frame.setVisible(true);
        });
    }
}

Explanation:

We use DefaultListModel to manage the items in the JList. This allows us to add and remove items dynamically at runtime.
New items are added to the list using addElement(), and selected items are removed using removeElement().

5. Customizing the Appearance of JList

You can customize the appearance of JList by changing its font, background, and foreground colors.

Example 5: Customizing JList Appearance

import javax.swing.*;
import java.awt.*;

public class JListExample5 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Custom JList Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 200);

            String[] items = {"Apple", "Banana", "Orange", "Grapes"};
            JList list = new JList<>(items);

            // Customize the appearance of the JList
            list.setFont(new Font("Serif", Font.BOLD, 16));
            list.setForeground(Color.BLUE); // Set text color to blue
            list.setBackground(Color.LIGHT_GRAY); // Set background color to light gray

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(new JScrollPane(list)); // Add the list with a scroll pane
            frame.setVisible(true);
        });
    }
}

Explanation:

We customize the font of the JList using setFont(), and we change the text color and background color using setForeground() and setBackground() respectively.

6. Working with Custom Objects in JList

JList can also handle custom objects. The toString() method of the object determines how the item is displayed in the list.

Example 6: Custom Objects in JList

import javax.swing.*;

class Item {
    private String name;
    private int id;

    public Item(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @Override
    public String toString() {
        return name;
    }

    public int getId() {
        return id;
    }
}

public class JListExample6 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Custom Objects in JList");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 200);

            // Create custom objects to store in the JList
            DefaultListModel listModel = new DefaultListModel<>();
            listModel.addElement(new Item("Apple", 1));
            listModel.addElement(new Item("Banana", 2));
            listModel.addElement(new Item("Orange", 3));
            listModel.addElement(new Item("Grapes", 4));

            JList list = new JList<>(listModel);
            JLabel label = new JLabel("Selected Item ID: ");

            // Add a ListSelectionListener to handle item selection
            list.addListSelectionListener(e -> {
                if (!e.getValueIsAdjusting()) {
                    Item selectedItem = list.getSelectedValue();
                    if (selectedItem != null) {
                        label.setText("Selected Item ID: " + selectedItem.getId());
                    }
                }
            });

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(new JScrollPane(list)); // Add the list with a scroll pane
            frame.add(label);
            frame.setVisible(true);
        });
    }
}

Explanation:

We create a custom Item class with a name and id. The toString() method is overridden to display the name in the list.
When an item is selected, we retrieve the full Item object and display its ID in the label.

7. Using JScrollPane with JList

JList does not automatically provide scrollbars, so it is often placed inside a JScrollPane to handle lists that exceed the visible area.

Example 7: Using JScrollPane with JList

import javax.swing.*;

public class JListExample7 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JList with JScrollPane");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300, 200);

            // Create a list of items
            String[] items = {"Apple", "Banana", "Orange", "Grapes", "Pineapple", "Mango", "Watermelon"};

            // Create a JList with the items
            JList list = new JList<>(items);

            // Add the JList to a JScrollPane
            JScrollPane scrollPane = new JScrollPane(list);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

            frame.setLayout(new java.awt.FlowLayout());
            frame.add(scrollPane);
            frame.setVisible(true);
        });
    }
}

Explanation:

We place the JList inside a JScrollPane to handle scrolling when the list exceeds the visible area.
The scroll pane automatically provides vertical scrollbars when needed.

Conclusion

JList is a versatile and powerful Swing component for displaying and selecting items from a list. It can be used to handle single and multiple selections, customize its appearance, and manage custom objects. You can also dynamically add or remove items and use a JScrollPane to handle long lists.

Summary of Key Points:

Basic JList: Create a list using new JList<>(items) to display a set of items.
Handling Events: Use ListSelectionListener to listen for selection changes and respond to user input.
Multiple Selection: Enable multiple item selection using setSelectionMode().
Add/Remove Items: Use DefaultListModel to dynamically add or remove items at runtime.
Custom Appearance: Customize fonts, background, and foreground colors of the JList.
Custom Objects: Store custom objects in the JList, and use the toString() method to display them.
Scroll Pane: Place the JList inside a JScrollPane to handle lists that exceed the visible area.

Related posts

Tutorial on Java GroupLayout in Swing

Tutorial on Java GridBagLayout in Swing

Tutorial on Java GridLayout in Swing