Creating Lists with JList Class

In this tutorial, we will introduce you a new widget in Swing called list. You will learn how to create lists using JList class.

A list is a widget that allows user to choose either a single selection or multiple selections. To create a list widget you use JList class. The JList class itself does not support scrollbar. In order to add scrollbar,  you have to use JScrollPane class together with JList class. The JScrollPane then manages a scrollbar automatically.

Here are the constructors of JList class:

JList ConstructorsMeaning
public JList()Creates an empty List.
public JList(ListModel listModel)Creates a list from a given model
public JList(Object[] arr)Creates a list that displays elements of a given array.
public JList(Vector<?> vector)Creates a list that displays elements of a given vector.

Example of creating a simple list using JList class

In this example, we will create a simple list that displays elements of an array. When user clicks the button, a dialog will display selected elements in the list. The getSelectedIndices() method is used to get selected indices and getElementAt() method is used to get element by index.

JList Demo
package jlistdemo1; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Main { public static void main(String[] args) { final int MAX = 10; // initialize list elements String[] listElems = new String[MAX]; for (int i = 0; i < MAX; i++) { listElems[i] = "element " + i; } final JList list = new JList(listElems); final JScrollPane pane = new JScrollPane(list); final JFrame frame = new JFrame("JList Demo"); // create a button and add action listener final JButton btnGet = new JButton("Get Selected"); btnGet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String selectedElem = ""; int selectedIndices[] = list.getSelectedIndices(); for (int j = 0; j < selectedIndices.length; j++) { String elem = (String) list.getModel().getElementAt(selectedIndices[j]); selectedElem += "\n" + elem; } JOptionPane.showMessageDialog(frame, "You've selected:" + selectedElem); }// end actionPerformed }); frame.setLayout(new BorderLayout()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(pane, BorderLayout.CENTER); frame.getContentPane().add(btnGet, BorderLayout.SOUTH); frame.setSize(250, 200); frame.setVisible(true); } }
Code language: PHP (php)