In this tutorials, we are going to learn about Java Swing JList component. JList is a component used to display a list of objects that allows the user to select one or more items.
Swing JList Example :
In this example, I am going to create a Colors list, and apply the background color by selecting the list item.
JListDemo.java
package com.onlinetutorialspoint.swing;
import java.awt.Color;
import java.awt.FlowLayout;
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 {
private JList jList;
// Creating list items
private static final String[] listItems = { "BLUE", "BLACK", "CYAN",
"GREEN", "GRAY", "RED", "WHITE" };
// Creating colors
private static final Color[] colors = { Color.BLUE, Color.BLACK,
Color.CYAN, Color.GREEN, Color.GRAY, Color.RED, Color.WHITE };
public JListDemo() {
super("JList Demo");
setLayout(new FlowLayout());
jList = new JList(listItems);
// set to single selection mode
jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// limit the visible row count of JList
jList.setVisibleRowCount(4);
add(new JScrollPane(jList));
jList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
getContentPane().setBackground(colors[jList.getSelectedIndex()]);
}
});
}
public static void main(String[] args) {
JListDemo jListDemo = new JListDemo();
jListDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jListDemo.setSize(350, 150);
jListDemo.setVisible(true);
}
}
Output :
Selected List Item with Green :
Changed the List Item with Gray:
Happy Learning 🙂