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

  • Was this tutorial helpful ?
  • YesNo