Java JList Class Example

JLIST

Java Swing Tutorial Explaining the JList Component. JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly—instead, the list must be associated with a scrollpane. The view port used by the scrollpane can also have a user-defined border. JList actions are handled using ListSelectionListener.

JLIST Example

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;

public class JListDemo extends JFrame {

	JList list;
	String[] listColorNames = { "black", "blue", "green", "yellow",
			"white" };
	Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN,
			Color.YELLOW, Color.WHITE };
	Container contentpane;
	public JListDemo() {
		super("List Source Demo");
		contentpane = getContentPane();
		contentpane.setLayout(new FlowLayout());
		list = new JList(listColorNames);
		list.setSelectedIndex(0);
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		contentpane.add(new JScrollPane(list));
		list.addListSelectionListener(new ListSelectionListener() {

			public void valueChanged(ListSelectionEvent e) {
				contentpane.setBackground(listColorValues[list
						.getSelectedIndex()]);
			}
		});
		setSize(200, 200);
		setVisible(true);
	}
	public static void main(String[] args) {
		JListDemo test = new JListDemo();
		test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}

Output

Download JList Source Code

JAVA JLIST CLASS

javax.swing Class Class JList
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JList
All Implemented Interfaces: 
Accessible, ImageObserver, MenuContainer, Scrollable, Serializable

JLIST CONSTRUCTOR

JList()
Constructs a JList with an empty model.

JList(ListModel dataModel)
Constructs a JList that displays the elements in the specified, non-null model.

JList(Object[] listData)
Constructs a JList that displays the elements in the specified array.

JList(Vector listData)
Constructs a JList that displays the elements in the specified Vector.

Like us on Facebook