7.5 The JList Class


The 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
figs/swng2.0708.gif

7.5.1 Properties

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

Table 7-9. JList properties

Property

Data type

get

is

set

Default value

accessibleContexto

AccessibleContext

·

   

JList.AccessibleJList

anchorSelectionIndex

int

·

     

cellRendererb

ListCellRenderer

·

 

·

From L&F

dragEnabled1.4

boolean

·

 

·

false

firstVisibleIndex

int

·

     

fixedCellHeightb

int

·

 

·

-1

fixedCellWidthb

int

·

 

·

-1

lastVisibleIndex

int

·

     

layoutOrientation1.4, b

int

·

 

·

VERTICAL

leadSelectionIndex

int

·

     

maxSelectionIndex

int

·

     

minSelectionIndex

int

·

     

modelb

ListModel

·

 

·

 

opaqueo

boolean

 

·

·

true

preferredScrollableViewportSizeo

Dimension

·

     

prototypeCellValueb

Object

·

 

·

null

scrollableTracksViewportHeighto

boolean

·

     

scrollableTracksViewportWidtho

boolean

·

     

selectedIndex

int

·

 

·

-1

selectedIndexi

boolean

 

·

   

selectedIndices

int[]

·

 

·

 

selectedValue

Object

·

     

selectedValues

Object[]

·

     

selectionBackgroundb

Color

·

 

·

null

selectionEmpty

boolean

 

·

 

true

selectionForegroundb

Color

·

 

·

null

selectionMode

int

·

 

·

MULTIPLE_INTERVAL_SELECTION

selectionModelb

ListSelectionModel

·

 

·

DefaultListSelec-tionModel

UIb

ListUI

·

 

·

From L&F

UIClassIDo

String

·

   

"ListUI"

valueIsAdjusting

boolean

·

 

·

false

visibleRowCount

int

·

 

·

8

1.4since 1.4, bbound, iindexed, ooverridden

See also properties from JComponent (Table 3-6).

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 Constants

Table 7-10 shows constants for the layoutOrientation property. These constants determine the layout of list elements.

Table 7-10. JList layoutOrientation constants

Constant

Data type

Description

VERTICAL

int

Indicates the default layout, a single column of cells

VERTICAL_WRAP

int

Indicates a multi-column layout with cells flowing vertically, then horizontally

HORIZONTAL_WRAP

int

Indicates a multi-column layout with cells flowing horizontally, then vertically

7.5.3 Constructors

public JList( )

Create an empty JList. Nothing can be added to this list without changing the model.

public JList(ListModel model)

Create a JList using the specified data model.

public JList(Object[] objects)

Create a JList using the array of objects passed in to populate a default data model.

public JList(Vector vector)

Create a JList using a Vector of objects passed in to populate a default data model.

7.5.4 Miscellaneous

public void ensureIndexIsVisible(int index)

Automatically scroll the viewport associated with the list until the element specified by index is visible.

public Rectangle getCellBounds(int index1, int index2)

Return a Rectangle object that outlines the area covered by the range of list elements. In the event that the range is invalid, the method returns null.

public int getNextMatch(String prefix, int startIndex, javax.swing.text.Position.Bias bias)

Starting with SDK 1.4, users can select items within lists by typing the first letter (or letters) of the contents of the cell that they'd like to select. This method was introduced to support that capability, but it can also be used from code. The arguments specify the textual prefix to be searched for, the index from which searching should begin (when the method is invoked in response to a user keypress, this will be the index selected last), and the direction in which searching should occur, which must be one of Position.Bias.Forward or Position.Bias.Backward. (Despite the unconventional capitalization, these are constants. In fact, they form a type-safe enumeration.)[3]

[3] If you're not familiar with this extremely useful Java pattern, learning about it is worth the price of Joshua Bloch's outstanding Effective Java Programming Language Guide (Addison-Wesley).

public String getToolTipText(MouseEvent event)

Since SDK 1.4, JList overrides this method to allow the tooltips of the underlying cells' renderers to appear when the mouse is held over a list cell. Note that if you call setToolTipText(null) on the list itself, you disable this feature from that point on.

public Point indexToLocation(int index)

Return a point representing the upper-left corner of the list element in local coordinates. In the event that the element is not currently displayed on the screen, or does not exist, the method returns null.

public int locationToIndex(Point p)

Return the index of the list element that contains the graphical point p.

7.5.5 Selection Model

public void setSelectionInterval(int index0, int index1)

Reset the selection interval to the inclusive range specified by the two indices passed in.

public void setSelectedValue(Object obj, boolean shouldScroll)

Set the list element that matches the reference obj as the only selection in the list. If shouldScroll is true, the list automatically scrolls to ensure that the element is visible.

public void addSelectionInterval(int index0, int index1)

Add the interval specified by the two indices passed in to the current selection.

public void removeSelectionInterval(int index0, int index1)

Remove the interval specified by the two indices passed in from the current selection.

public void clearSelection( )

Clear the entire selection.

7.5.6 Scrolling

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

public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)

If the orientation is vertical, this method returns the height of the visibleRect rectangle. If the orientation is horizontal, this method returns the width. The direction variable is not used.

public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)

Return the number of pixels it takes to expose the next element in the list. If direction is positive, it is assumed that the user is scrolling downwards, and the method returns the height of the first element that is visible or partially visible on the list. If the direction is negative, it is assumed that the user is scrolling upwards, and the method returns the height of the last element that is visible or partially visible on the list.

7.5.7 Data Model

public void setListData(Object[] objects)

Create a ListDataModel from the array of objects passed in and resets the current data model of the JList to reference it.

public void setListData(Vector vector)

Create a ListDataModel from the vector of objects passed in and resets the current data model of the JList to reference it.

7.5.8 User Interface

public void updateUI( )

A new L&F has been selected by the user. Invoking this method forces the component to reset its UI delegate.

7.5.9 Events

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

public void addListSelectionListener(ListSelectionListener)
public void removeListSelectionListener(ListSelectionListener)

Add or remove a selection listener from the event registration list.

public ListSelectionListener[] getListSelectionListeners( )

Available since SDK 1.4, this method returns the list of registered listeners.

7.5.10 The Java Books Example

Here 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
figs/swng2.0709.gif

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.



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