I l@ve RuBoard |
![]() ![]() |
7.5 The JList ClassThe JList class is the generic Swing implementation of a list component. In the default selection mode, you can make multiple selections by clicking with the mouse while holding down the modifier key defined by the current L&F (generally Shift for a single, contiguous range and Ctrl or Command for noncontiguous selections). The JList class does not provide scrolling capabilities, but it can be set as the viewport of a JScrollPane to support scrolling. Figure 7-8 shows the JList component in four different L&Fs. Figure 7-8. The JList component in four L&Fs![]() 7.5.1 PropertiesThe JList class essentially combines the features of the data model, the selection model, and the cell renderer into a single Swing component. The properties of the JList class are shown in Table 7-9.
The model property contains an object that implements the ListModel interface; this object holds the element data of the list. If you don't supply a model (or the data from which to build a model) when you construct the JList, a useless default is created that contains zero entries (and cannot be added to). The selectionModel property contains an object that implements the ListSelectionModel interface; this object manages the current selections in the list. Both interfaces were covered earlier in the chapter. The selectionMode mirrors the selectionMode property of the ListSelectionModel. This property indicates how many ranges can be selected at a time. The selectionForeground and selectionBackground properties set the foreground and background colors of the selected cells. The opaque property is always set to true to indicate that the JList is opaque. The firstVisibleIndex property represents the topmost, leftmost (assuming a Western componentOrientation) element that is at least partially visible in the list's "window," while the lastVisibleIndex property represents the bottommost, rightmost (again, depending on the componentOrientation and layoutOrientation properties) element that is at least partially visible. visibleRowCount indicates the number of elements currently visible in the list. You can set this property to ensure that the list shows no more than a certain number of elements at a time. The next series of properties mirrors those in the ListSelectionModel. The anchorSelectionIndex and leadSelectionIndex give the anchor and lead positions for the most recent selection. The minSelectionIndex and maxSelectionIndex give the smallest and largest indices of all selected components. selectedIndex gives the first selected index in the list (or -1 if there is none) while selectedIndices holds an ordered integer array of all current selections. There is also an indexed selectedIndex property that indicates whether a specific index is selected. The selectedValue property lets you retrieve the first selected object, and selectedValues lets you retrieve an array that contains all the selected objects. Finally, the selectionEmpty property is a boolean that tells whether there are any elements currently selected. The fixedCellHeight and fixedCellWidth properties allow the user to explicitly set a fixed height in pixels for the cells in the list. The prototypeCellValue is a reference to an object that the list can use to calculate the minimum width of every cell in the list; you can use this property to define the size needed for each cell. This keeps the list from having to compute the size by checking each item in the list and can greatly speed up drawing. For example, you might set this property to the string "mmmmm" to ensure that each cell could contain five characters. The preferredScrollableViewportSize property indicates the Dimension necessary to support the visibleRowCount property. The valueIsAdjusting property is used to indicate that a series of ListSelectionEvent objects is being generated by the selection model, such as when a drag is occurring. The scrollableTracksViewportWidth and scrollableTracksViewportHeight properties report whether the JList is resized to match the size of the viewport containing it. They are true if the preferred size of the JList is smaller than the viewport (in the appropriate direction), allowing a JList to stretch. They are false if the JList is larger than the viewport. The standard JScrollPane's scrollbars become active when these properties become false. SDK 1.4 introduced two new properties: dragEnabled and layoutOrientation.drag-Enabled can be set to true to turn on the new automatic Drag and Drop support. For this to work, the L&F must support Drag and Drop, and you need to set the component's transferHandler, as discussed in Chapter 24. (Note that even though you'd expect to use "isDragEnabled" to retrieve the value of a boolean property, JList defines getDragEnabled instead.) Lists can now have more than one column. The layoutOrientation property controls this and determines in what order the cells should "flow" when there is more than one column. Its value must be one of the constants defined in Table 7-10. To support internationalization, layoutOrientation interacts with JComponent's componentOrientation property to determine cell layout. 7.5.2 ConstantsTable 7-10 shows constants for the layoutOrientation property. These constants determine the layout of list elements.
7.5.3 Constructors
7.5.4 Miscellaneous
7.5.5 Selection Model
7.5.6 ScrollingThe following methods are used for internal configuration purposes. Along with the getPreferredScrollableViewportSize( ), getScrollableTracksViewportHeight( ), and getScrollableTracksViewportWidth( ) methods (accessors for three of the properties listed in Table 7-9), these methods implement the Scrollable interface. Scrollable allows a JScrollPane to be more intelligent about scrolling. You would rarely call these methods.
7.5.7 Data Model
7.5.8 User Interface
7.5.9 EventsThe JList component fires a ListSelectionEvent when any of its selections change. These methods mirror the ListSelectionEvents that are fired directly from the selection model and are used to notify any selection listeners that have registered directly with the JList itself. The source of the event is always the JList object.
7.5.10 The Java Books ExampleHere is the code for the list displaying some O'Reilly Java books. It uses the BookEntry and BookCellRenderer classes. // ListExample.java // import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ListExample extends JPanel { private BookEntry books[] = { new BookEntry("Ant: The Definitive Guide", "covers/ant.gif"), new BookEntry("Database Programming with JDBC and Java", "covers/jdbc.gif"), new BookEntry("Developing Java Beans", "covers/beans.gif"), new BookEntry("Developing JSP Custom Tag Libraries", "covers/jsptl.gif"), new BookEntry("Java 2D Graphics", "covers/java2d.gif"), new BookEntry("Java and XML", "covers/jxml.gif"), new BookEntry("Java and XSLT", "covers/jxslt.gif"), new BookEntry("Java and SOAP", "covers/jsoap.gif"), new BookEntry("Java and XML Data Binding", "covers/jxmldb.gif"), new BookEntry("Java Cookbook", "covers/jcook.gif"), new BookEntry("Java Cryptography", "covers/jcrypto.gif"), new BookEntry("Java Distributed Computing", "covers/jdist.gif"), new BookEntry("Java I/O", "covers/javaio.gif"), new BookEntry("Java in a Nutshell", "covers/javanut.gif"), new BookEntry("Java Management Extensions", "covers/jmx.gif"), new BookEntry("Java Message Service", "covers/jms.gif"), new BookEntry("Java Network Programming", "covers/jnetp.gif"), new BookEntry("Java Performance Tuning", "covers/jperf.gif"), new BookEntry("Java RMI", "covers/jrmi.gif"), new BookEntry("Java Security", "covers/jsec.gif"), new BookEntry("JavaServer Pages", "covers/jsp.gif"), new BookEntry("Java Servlet Programming", "covers/servlet.gif"), new BookEntry("Java Swing", "covers/swing.gif"), new BookEntry("Java Threads", "covers/jthread.gif"), new BookEntry("Java Web Services", "covers/jws.gif"), new BookEntry("Learning Java", "covers/learnj.gif") }; private JList booklist = new JList(books); public ListExample( ) { setLayout(new BorderLayout( )); JButton button = new JButton("Print"); button.addActionListener(new PrintListener( )); booklist = new JList(books); booklist.setCellRenderer(new BookCellRenderer( )); booklist.setVisibleRowCount(4); JScrollPane pane = new JScrollPane(booklist); add(pane, BorderLayout.NORTH); add(button, BorderLayout.SOUTH); } public static void main(String s[]) { JFrame frame = new JFrame("List Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(new ListExample( )); frame.pack( ); 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[] = booklist.getSelectedIndices( ); System.out.println("Selected Elements: "); for (int i=0; i < selected.length; i++) { BookEntry element = (BookEntry)booklist.getModel( ).getElementAt(selected[i]); System.out.println(" " + element.getTitle( )); } } } } The code to create the list is relatively short. The list is instantiated with an array of entries that encapsulate the titles and images. In our constructor, we inform the JList to use our example cell renderer to display each of the books in the list. Finally, we add the list to a JScrollPane object to allow support for scrolling. The result appears in Figure 7-9. Figure 7-9. A complete JList with a custom cell renderer![]() We added a Print button that extracts and prints the titles of all selected books. Using custom classes to encapsulate multi-part information is a major benefit of object-oriented code, and, as this example illustrates, JList makes it pretty easy to work with and display such composite building blocks. |
I l@ve RuBoard |
![]() ![]() |