7.1 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.

Figure 7-1. A simple Swing list
figs/swng2.0701.gif
//  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);     }     public static void main(String s[]) {          JFrame frame = new JFrame("Simple List Example");          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          frame.setContentPane(new SimpleList( ));          frame.setSize(250, 200);          frame.setVisible(true);     }     // An inner class to respond to clicks of the Print button     class PrintListener implements ActionListener {         public void actionPerformed(ActionEvent e) {             int selected[] = list.getSelectedIndices( );             System.out.println("Selected Elements:  ");             for (int i=0; i < selected.length; i++) {                 String element =                       (String)list.getModel( ).getElementAt(selected[i]);                 System.out.println("  " + element);             }         }     } }

Take a close look at the source. The first thing you might notice is that we embedded the Swing list inside the viewport of a scrollpane object. The Swing JList class itself does not support scrolling through its data. Instead, it hands off the responsibility to the JScrollPane class. This is a significant design change from its predecessor, java.awt.List, which automatically managed a scrollbar for you. However, making a list the view of a scrollpane object fits better into the overall modular philosophy of Swing. The clear separation of function allows developers to reuse a customized scrollbar (or scrollpane) with their own lists instead of simply accepting a default provided with the list component. It also enables autoscrolling support, so you can drag the mouse above or below the list, and its contents scroll automatically.

Try selecting multiple numbers (you can do this in most L&Fs by holding down the Shift key while clicking). Note that by using Shift you can select only one range, or continuous set of numbers, at a time. If you select a number beyond the current selection range, the range is extended to cover everything in between. The first number selected (i.e., the one you didn't have to hold Shift down for) becomes the initial endpoint for the range. This endpoint is called the anchor. The most recent selection (which is outlined) forms the second endpoint. This element is called the lead. Together, the anchor and the lead form a range of selections in the list, as shown in Figure 7-2.

Figure 7-2. The anchor and lead positions in a list selection
figs/swng2.0702.gif

When the user presses the button, an actionPerformed( ) method is called. This method reports all the items that are currently selected in the list:

Selected Elements:   Four   Five   Six   Seven   Eight 

There is also a way to make discontiguous selections (so you could select Four, Six, and Eight through Ten, for example). This is done by holding down a different modifier key: on Unix and Windows this is typically the Control key while on the Macintosh the Command (Apple) key is used. As usual, these differences are managed by the L&F. Since 1.3, the default behavior for a list is to support both ranges and discontiguous selections. Prior versions allowed only a single range. All versions let you override the default.

If you are using SDK 1.4 or later, you can also select elements in the list by typing the first characters in their label.

7.1.1 Anatomy of a Swing List

Now that we've seen the basics, let's take a closer look at JList. Figure 7-3 shows a high-level class diagram for Swing's list classes. In particular, note the three interfaces in the middle.

Figure 7-3. Swing list class diagram
figs/swng2.0703.gif

Each list component consists of three parts, as shown in Figure 7-4. The first of the three parts is the elements that comprise the list, called the list data. As you might guess, the list data is assigned to a model an object implementing the ListModel interface represents the list data. By default, JList uses the DefaultListModel class, an implementation of ListModel that stores a collection of data objects in a Vector. If you want a model more specific to your needs, the most convenient way to do it is to extend the AbstractListModel class and add your specific functionality to the basic housekeeping it provides.

Figure 7-4. The three parts of a Swing list
figs/swng2.0704.gif

The second element is a model as well; however, this one represents the user's selections. The model interface for selection data is the ListSelectionModel. Like the list data model, it also has a standard implementation: DefaultListSelectionModel . With the default JList, for example, you can select several ranges simultaneously. However, you can also program the DefaultListSelectionModel to allow only one element to be selected at a given time.

The final piece is called a cell renderer . A cell renderer defines how each cell displays its data in the list, including when the cell is selected. Why an entire class for rendering list elements? As we mentioned previously, list data is not constrained to strings. Icons and animations can be displayed in place of or next to descriptive text. In many Swing components, a cell renderer is a common way to render complex data, or any data in a way that's specific to your application. If you write one carefully, it can be reused in several locations.

7.1.2 Where to Go from Here?

The following sections outline the various models and support classes that make up a Swing list. If you simply want to get to know the Swing JList class, you can skip ahead to Section 7.5, where we create a graphical list of some O'Reilly Java books. On the other hand, if you want to learn more about the data and selection models of the JList, then read on!



Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net