JList: Displaying a List of Items
JList is used to show a list of items, such as days of the week, from which the user can select one or more entries.
Example: Days of the Week in a JList
This example stores days of the week in a string array and passes it to aJList. A label describes what the list represents.
import javax.swing.*;
import java.awt.*;
class MyFrame extends JFrame {
MyFrame() {
setTitle("Components - JList");
String week[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
JList<String> l1 = new JList<String>(week);
JLabel lb = new JLabel("Select The Day:");
add(lb);
add(l1);
setLayout(new FlowLayout());
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class JListDemo {
public static void main(String arr[]) {
new MyFrame();
}
}What is JList?
A JList shows a list of values from which the user can select. It is useful for any situation where choices can be displayed in a vertical list.
- Displays an array or list of items (e.g., days, names).
- Supports single or multiple selection (by default single selection).
- Often combined with scroll panes when the list is long.
Line-by-line: Understanding the JList example
The JFrame setup is the same pattern as previous components. Here we focus on how the array and JList are created and connected.
String week[] = Saturday;
Creates a string array containing all days of the week. This will be the data source for the list.
JList<String> l1 = new JList<String>(week);
Creates a list component that displays each string from theweek array as a separate item.
JLabel lb = new JLabel("Select The Day:");
add(lb);
add(l1);
Creates a label that explains what the list is for, then adds the label and the JList to the frame so they appear side by side withFlowLayout.
Where JList is used
Lists are useful when you have a fixed set of options that are best shown stacked vertically. In more advanced GUIs, JList is often combined with models and scroll panes.