How do I get the items of a JList components?

In this example you can see how we can read the items of a JList component. We also obtain the size or the number of items in the JList components.

This can be done by calling JList‘s getModel() method which return a ListModel object. From the ListModel we can get the items size, and we can iterate the entire items of the JList component.

package org.kodejava.swing;

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

public class JListGetItems extends JFrame {
    public JListGetItems() {
        initialize();
    }

    public static void main(String[] args) {
        // Run the program, create a new instance of JListGetItems and
        // set its visibility to true.
        SwingUtilities.invokeLater(
                () -> new JListGetItems().setVisible(true));
    }

    private void initialize() {
        // Configure the frame default close operation, its size and the
        // layout.
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setSize(500, 500);
        this.setLayout(new BorderLayout(5, 5));

        // Create a JList and set the items to the available weekdays
        // names.
        Object[] listItems = DateFormatSymbols.getInstance().getWeekdays();
        JList<Object> list = new JList<>(listItems);
        getContentPane().add(list, BorderLayout.CENTER);

        // Below we start to print the size of the list items and iterates
        // the entire list items or elements.
        System.out.println("JList item size: " + list.getModel().getSize());

        System.out.println("Reading all JList items:");
        System.out.println("-----------------------");
        for (int i = 0; i < list.getModel().getSize(); i++) {
            Object item = list.getModel().getElementAt(i);
            System.out.println("Item = " + item);
        }
    }
}

And here is the result:

JList item size: 8
Reading all JList items:
-----------------------
Item = 
Item = Sunday
Item = Monday
Item = Tuesday
Item = Wednesday
Item = Thursday
Item = Friday
Item = Saturday
Wayan

Leave a Reply

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