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");
		add(displayButton);
		
		
		// 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);
		myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		myList.setLayoutOrientation(JList.VERTICAL);
		myList.setVisibleRowCount(3);
		
		JScrollPane scrollPane = new JScrollPane(myList);

		// Add the JScrollPane to the frame
		add(scrollPane);

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

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

}

Output:

How to use Jlist in Java swing

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

Sharing Is Caring: