Java JList Example
In this example we are going to demonstrate how to use Java Swing JList
, JList
is a Swing component with which we can display a list of elements. This component also allows the user to select one or more elements visually. This article shows how to work with JList
features using a simple example where we build a GUI with a JList
to show a list of employee names and let us add/remove a single name to/from the JList
dynamically.
1. Swing JList:
We create a custom JList
SwingJList.java
where we can initialize the data model, customize the selection mode and enable scrolling.
JList Data Model:
As with other Swing components, the data for a
JList
is held in a model. This is represented byListModel
interface in the Swing API. The API provides a default implementation of this class namedDefaultListModel
. So, We create an instance of theDefaultListModel
class by declaring it as acceptingT
as a parameterized raw type using Java Generics. Also, we added two additional methodsaddElement(T element)
andremoveElement(T element)
which implicitly useadd(int index, E element)
andremoveElement(Object obj)
to let us add/remove elements to/from theJList
model.public SwingJList(List<T> listData) { // Create a JList data model super(new DefaultListModel<T>()); listData.forEach(element -> addElement(element)); } public void addElement(T element) { ((DefaultListModel<T>) getModel()).add(Constants.NEW_ELEMENT_IDX, element); } public void removeElement(Object element) { ((DefaultListModel<T>) getModel()).removeElement(element); }
JList Selection Mode:
The
JList
selection mode defines the way elements can be selected,JList
uses an instance ofListSelectionModel
to manage its selection. By default, aJList
selection model isMULTIPLE_INTERVAL_SELECTION
but we can specify a different selection mode by calling thesetSelectionMode
method on theJList
. There are totally 3 selection modes available to be set for theJList
:- Single Selection Mode:
This mode specifies that only a single item can be selected at any point of time, we can activate this mode as the following:setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- Single Interval Selection Mode:
This mode specifies that multiple items can be selected, but they have to be contiguous. Items can be selected contiguously by pressing down the shift key and selecting elements with the mouse, we can activate this mode as the following:setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
- Multiple Interval Selection Mode:
This mode is the default mode. This mode specifies that multiple items can be selected and they may or may not be contiguous, we can activate this mode as the following:setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
- Single Selection Mode:
JList Scrolling:
JList
doesn’t support scrolling directly. To create a scrollingJList
, we have to add theJList
to aJScrollPane
, as the following:JScrollPane listScrollPane = new JScrollPane(simpleSwingJList);
SwingJList.java:
package com.jcg; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.ListSelectionModel; /** * @author ashraf * @param <T> * */ @SuppressWarnings("serial") public class SwingJList<T> extends JList<T> { public SwingJList(List<T> listData) { // Create a JList data model super(new DefaultListModel<T>()); listData.forEach(element -> addElement(element)); // Set selection mode setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } public void addElement(T element) { ((DefaultListModel<T>) getModel()).add(Constants.NEW_ELEMENT_IDX, element); } public void removeElement(Object element) { ((DefaultListModel<T>) getModel()).removeElement(element); } }
2. JList Selection Listener:
The ListSelectionListener
fires the event if the user selecting or deselecting an item. The below code registers a ListSelectionListener
using the addListSelectionListener(ListSelectionListener listener)
method. We use an anonymous inner class to implement the event listener interface. We implement the valueChanged(ListSelectionEvent e)
method. We call the handy method getSelectedValue()
on the JList
instance which returns the current selected employee name, we simply show it in the input text box.
swingJList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { String selectedName = swingJList.getSelectedValue(); nameField.setText(selectedName); } } });
3. Adding/Removing JList Items:
We add/remove items to/from the JList
via Swing component event listeners, we just register an event listener to be notified when add or remove event happens. we create the following two ActionListener
where we add one on the addButton
and the other on the deleteButton
JButton
.
- Add Action Listener:
We createaddButton
JButton
to add a new employee name to theJList
, we register anActionListener
, then we implement theactionPerformed(ActionEvent e)
method to add a single employee name to our employees list. Now, we can write any employee name in the input text box and click theAdd Employee
button to be added to the employees list.JButton addButton = new JButton("Add Employee"); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String name = nameField.getText(); if (name != null && !"".equals(name)) { swingJList.addElement(name); } else { JOptionPane.showMessageDialog(null, "Employee name is empty", "Error", JOptionPane.ERROR_MESSAGE); } } });
- Delete Action Listener:
We createdeleteButton
JButton
to remove selected employee name from theJList
, we register anActionListener
, then we implement theactionPerformed(ActionEvent e)
method to remove a single employee name from our employees list. Now, we can select a single employee name and click theDelete Employee
button to be removed from the employees list.JButton deleteButton = new JButton("Delete Employee"); deleteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String name = nameField.getText(); if (name != null && !"".equals(name)) { swingJList.removeElement(name); } else { JOptionPane.showMessageDialog(null, "Please, select employee name from the list", "Warning", JOptionPane.WARNING_MESSAGE); } } });
4. JList Demo:
We create SwingJListDemo.java
class to test our example. Also, we add a supplementary Constants.java
class contains constants used through our code.
SwingJListDemo.java:
package com.jcg; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /** * @author ashraf_sarhan * */ public class SwingJListDemo { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { setLookAndFeel(Constants.NIMBUS_LF); createAndShowGUI(); } catch (Exception e) { e.printStackTrace(); } } }); } public static void createAndShowGUI() throws Exception { JFrame frame = new JFrame("Swing JList Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create JList with a List of String names SwingJList<String> swingJList = new SwingJList<>( Arrays.asList(Constants.LIST_DATA)); JTextField nameField = new JTextField(26); // Adding a list selection listener swingJList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { String selectedName = swingJList.getSelectedValue(); nameField.setText(selectedName); } } }); // Create an action listener to add a new item to the List JButton addButton = new JButton("Add Employee"); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String name = nameField.getText(); if (name != null && !"".equals(name)) { swingJList.addElement(name); } else { JOptionPane.showMessageDialog(null, "Employee name is empty", "Error", JOptionPane.ERROR_MESSAGE); } } }); // Create an action listener to remove existed item from the List JButton deleteButton = new JButton("Delete Employee"); deleteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String name = nameField.getText(); if (name != null && !"".equals(name)) { swingJList.removeElement(name); } else { JOptionPane.showMessageDialog(null, "Please, select employee name from the list", "Warning", JOptionPane.WARNING_MESSAGE); } } }); // Put the JList in a JScrollPane to handle scrolling JScrollPane listScrollPane = new JScrollPane(swingJList); listScrollPane.setPreferredSize(new Dimension(250, 200)); listScrollPane.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Employees List", TitledBorder.CENTER, TitledBorder.TOP)); // Create a control panel JPanel buttonPane = new JPanel(); buttonPane.add(nameField); buttonPane.add(addButton); buttonPane.add(deleteButton); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane, buttonPane); splitPane.setDividerLocation(250); splitPane.setEnabled(false); frame.add(splitPane); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void setLookAndFeel(String lf) throws Exception { // Set Nimbus as L&F try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if (lf.equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { // If Nimbus is not available, you can set the GUI the system // default L&F. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } } }
Constants.java:
package com.jcg; /** * @author ashraf_sarhan * */ public class Constants { public static final String NIMBUS_LF = "Nimbus"; public static final String[] LIST_DATA = { "Ashraf Sarhan", "Sara Mohamed", "Esraa Ahmed", "Ghada Mohamed", "Dalia Osama", "Amira Mohamed", "Sama Karim", "Nada Ahmed", "Ahmed Farrag", "Mohamed Senussi", "Nehal Taha", "Ahmed Sarhan", "Khaled Mohamed" }; public static final int NEW_ELEMENT_IDX = 0; }
Output:
5. Download the Source Code of this example:
This was an example on how to use Java Swing JList
.
You can download the full source code of this example here: SwingJListExampleCode.zip