JList

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.

  1. JList Data Model:

    As with other Swing components, the data for a JList is held in a model. This is represented by ListModel interface in the Swing API. The API provides a default implementation of this class named DefaultListModel. So, We create an instance of the DefaultListModel class by declaring it as accepting T as a parameterized raw type using Java Generics. Also, we added two additional methods addElement(T element) and removeElement(T element) which implicitly use add(int index, E element) and removeElement(Object obj) to let us add/remove elements to/from the JList 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);
    }
    
  2. JList Selection Mode:

    The JList selection mode defines the way elements can be selected, JList uses an instance of ListSelectionModel to manage its selection. By default, a JList selection model is MULTIPLE_INTERVAL_SELECTION but we can specify a different selection mode by calling the setSelectionMode method on the JList. There are totally 3 selection modes available to be set for the JList:

    1. 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);
      

      Figure 1: Single Selection Mode
      Figure 1: Single Selection Mode
    2. 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);
      

      Figure 2: Single Interval Selection Mode
      Figure 2: Single Interval Selection Mode
    3. 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);
      

      Figure 3: Multiple Interval Selection Mode
      Figure 3: Multiple Interval Selection Mode
  3. JList Scrolling:

    JList doesn’t support scrolling directly. To create a scrolling JList, we have to add the JList to a JScrollPane, 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.

  1. Add Action Listener:
    We create addButton JButton to add a new employee name to the JList, we register an ActionListener, then we implement the actionPerformed(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 the Add 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);
    		}
    	}
    });
    
  2. Delete Action Listener:
    We create deleteButton JButton to remove selected employee name from the JList, we register an ActionListener, then we implement the actionPerformed(ActionEvent e) method to remove a single employee name from our employees list. Now, we can select a single employee name and click the Delete 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:

Figure 4: Swing JList Demo
Figure 4: Swing JList Demo

5. Download the Source Code of this example:

This was an example on how to use Java Swing JList.

Download
You can download the full source code of this example here: SwingJListExampleCode.zip

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button