How to use JList in Java Swing

JList is a Swing component in Java that allows you to display a list of items in a graphical user interface.

Following is a basic example of how to use JList in Java Swing:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class JListDemo extends JFrame {

	public JListDemo() {

		setLayout(new FlowLayout());
		JButton displayButton = new JButton("Display");
		// Create an array of items to display in the JList
		String[] items = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };

		// Create a new JList and add it to a JScrollPane
		JList<String> myList = new JList<String>(items);
		JScrollPane scrollPane = new JScrollPane(myList);

		// Add the JScrollPane to the frame

		// Set frame properties and show it
		setTitle("JList Demo");
		setSize(300, 200);
		displayButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("Your selected value is: "+myList.getSelectedValue());

	public static void main(String[] args) {
		new JListDemo();



How to use Jlist in Java swing
How to use JList in Java Swing 2

When, user selects the item from the list and clicks the display button it prints the selected item’s value in the console.