Introduction to JList

May 2, 2018 Oclemy Java JList 3 minutes, 41 seconds

A JList is a swing component that displays a list of objects and allows the user to select one or more items.

JLists are like the ListViews in other programming languages in that it allows us represent lists of items.

API Definition

JList is defined in the javax.swing package.

package javax.swing;

JList is generic. Moreover it inherits from javax.swing.JComponent, which is an abstract class that is the base class for all Swing components except top-level containers.

public class JList<E> extends JComponent implements Scrollable, Accessible

Moreover as you can see JList implements the javax.swing.Scrollable, an interface that provides information to a scrolling container like JScrollPane, and javax.swing.Accessible,which is the main interface for the accessibility package.

Adding Data to JList

We don't append data directly to JLists. Instead we use a separate model(A ListModel). That model will then maintain the contents of the list.

However, if you want to rendr items from an array or a vector, then we just pass the Array in our JLIst constructor then the JList will automatically build the ListModel for us.

 String[] data = {"Mercury", "Venus", "Earth", "Mars"};
 JList<String> myList = new JList<String>(data);

Working with a ListModel

However majority of time you want to use a ListModel if you have data coming from other collections.

Moreover the ListModel defines several methods that we can aso use to manipulate our data.

We can instantiate the ListModel in the following way:

DefaultListModel defaultListModel=new DefaultListModel();

DefaultListModel is defined in the javax.swing package.

Then we can loop through items, say that we have in an arraylist and add them to our DefaultListModel:

        getItems().stream().forEach((star) -> {
            defaultListModel.addElement(star);
        });

Then set the list model to our JList instance via the setModel() method:

myJList.setModel(defaultListModel);

Example - Populate JList from an Array using a ListModel, then Handle ItemClicks.

We want to populate our JList from a DefaultListModel and listen to selected valueChanged events and show the selected item in a JOptionPane dialog.

Main.java


package info.camposha;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

public class Main extends javax.swing.JFrame {

    String[] stars = { "UY Scuti", "VY Canis Majoris","VV Cephei A","NML Cygni",  "Betelgeuse","Antares A","Rigel","Adebaran",
        "Arcturus","Sirius", "Epsilon Canis Majos","VX Sagittarii","AH Scorpii","PZ Cassiopeiae","EV Carinae","CE Tauri","The Pistol Star","Polaris" };
    DefaultListModel defaultListModel=new DefaultListModel();

    public Main() {
        initComponents();
        this.bindData();
    }
    private void bindData(){
        for (String star : stars) {
            defaultListModel.addElement(star);
        }
        myJList.setModel(defaultListModel);
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        myJList = new javax.swing.JList<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Java JList - Camposha.info");
        setBackground(new java.awt.Color(240, 77, 67));
        setPreferredSize(new java.awt.Dimension(435, 509));
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(0, 153, 104));

        myJList.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });
        myJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                myJListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(myJList);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(71, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(65, 65, 65)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(85, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(457, Short.MAX_VALUE))
        );

        pack();
    }                        

    private void myJListValueChanged(javax.swing.event.ListSelectionEvent evt) {                                     
        JOptionPane.showMessageDialog(rootPane, myJList.getSelectedValue(), "Selected Star", JOptionPane.INFORMATION_MESSAGE);
    }                                    

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(() -> {
            new Main().setVisible(true);
        });
    }
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList<String> myJList;
}

Result JList Selected Item

Best Regards.

Comments