O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Lists

A list is a graphical component that presents the user with choices. Lists typically display several items at a time, allowing the user to make either a single selection or multiple selections. In the event that the inventory of the list exceeds the space available to the component, the list is often coupled with a scrollpane to allow navigation through the entire set of choices.

The Swing JList component allows elements to be any Java class capable of being rendered—which is to say anything at all because you can supply your own renderer. This offers a wide range of flexibility; list components can be as simple or as complex as the programmer’s needs dictate.

Let’s get our feet wet with a simple list. The following example uses the Swing list class, JList, to create a single-selection list composed only of strings. Figure 7-1 shows the result.

A simple Swing list

Figure 7-1. A simple Swing list

// SimpleList.java // import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SimpleList extends JPanel { String label[] = { "Zero","One","Two","Three","Four","Five","Six", "Seven","Eight","Nine","Ten","Eleven" }; JList list; public SimpleList( ) { this.setLayout(new BorderLayout( )); list = new JList(label); JScrollPane pane = new JScrollPane(list); JButton button = new JButton("Print"); button.addActionListener(new PrintListener( )); add(pane, BorderLayout.CENTER); add(button, BorderLayout.SOUTH); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required