Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...

Swing Chapter 10. (The basics) List Boxes. Easy for reading, Click here!

Custom Search
Swing Chapter 10. (The basics) List Boxes. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 1/5 

Next Page (2/5) Next Page

Chapter 10. List Boxes

Subpages: 1. JList API overview  
Basic JList example 
Custom rendering 
4. Processing keyboard input and searching 
5. List of check boxes 

In this chapter:

  •          JList
  •          Basic JList example
  •          Custom renderer
  •          Processing keyboard input and searching
  •          List of check boxes

10.1  JList API overview

class javax.swing.JList

This class represents a basic GUI component allowing the selection of one or more items from a list of choices. JList has two models: ListModel which handles data in the list, and ListSelectionModel which handles item selection (three different selection modes are supported which we will discuss below). JList also supports custom rendering, as we learned in the last chapter, through the implementation of the ListCellRenderer interface. We can use existing default implementation of ListCellRenderer (DefaultListCellRenderer) or create our own according to our particular needs (which we will see later in ths chapter). Note that unless we use a custom renderer, the default renderer will display each element as a String defined by that object's toString() method (the only exceptions to this are Icon implementations which will be renderered as they would be in any JLabel). Also note that a ListCellRenderer returns a Component, but that component is not interactive and is only used for display purposes (i.e. it acts as a "rubber stamp"API). For instance, if a JCheckBox is used as a renderer we will not be able to check and uncheck it. Unlike JComboBox, however, JList does not support editing of any sort.

A number of constructors are available to create a JList component. We can use the default constructor or pass list data to a constructor as a one-dimensional array, a Vector, or as an implementation of the ListModel interface. The last variant provides maximum control over a list's properties and appearance. We can also assign data to a JList using the setModel() method, or one of the overloaded setListData() methods.

JList does not provide direct access to its elements, and we must access its ListModel to gain access to this data. JList does, however, provide direct access to its selection data by implementing all ListSelectionModel methods, and delegating their traffic to the actual ListSelectionModel instance. To avoid repetition we will discuss selection funcionality below in our overview of ListSelectionModel.

JList maintains selection foreground and background colors (assigned by its UI delegate when installed), and the default cell renderer, DefaultListCellRenderer, will use these colors to render selected cells. These colors can be assigned with setSelectedForeground() and setSelectedBackground(). Nonselected cells will be rendered with the component foreground and background colors assigned to JList with setForeground() and setBackground().

JList implements the Scrollable interface (see chapter 7) to provide vertical unit incremental scrolling corresponding the list cell height, and vertical block incremental scrolling corresponding to the number of visible cells. Horizontal unit increment scrolling corresponds to the size of the list's font (1 if the font is null), and horizontal block unit increment scrolling corresponds to the current width of the list. Thus JList does not directly support scrolling and is intended to be placed in a JScrollPane.

The visibleRowCount property specifies how many cells should be visible when a JList is placed in a scroll pane. This defaults to 8 and can be set with the setVisibleRowCount() method. Another interesting method provided by JList is ensureIndexIsVisible(), which forces the list to scroll itself so that the element corresponding to the given index becomes visible. Note that JList also supports autoscrolling (i.e. it will scroll element by element every 100ms if the mouse is dragged below or above its bounds and if an item has been selected).

By default the width of each cell is the width of the widest item, and the hieght of each cell corresponds to the hieght of the tallest item. We can overpower this behavior and specify our own fixed cell width and height of each list cell using the setFixedCellWidth() and setFixedCellHeight() methods.

Another way to control the width and height of each cell is through use of the setPrototypeCellValue() method. This method takes an Object parameter and uses it to automatically determine the fixedCellWidth and fixedCellHeight. A typical use of this method would be to give it a String. This forces the list to use a fixed cell width and hieght equal to the width and hieght of that string when rendered in the Font currently assigned to the JList.

JList also provides a method called locationToIndex() which will return the index of a cell at the given Point (in list coordinates). -1 will be returned if none is found. Unfortunately JList does not provide support for double-clicking, but this method comes in very handy in implementing our own. The following psuedocode shows how we can use a MouseAdapter, MouseEvent, and the locationToIndex() method to determine the JList cell a double-click occurs on:

  myJist.addMouseListener( new MouseAdapter() {

    public void mouseClicked(MouseEvent e) {

      if (e.getClickCount() == 2) {

        int cellIndex = myJList.locationToIndex(e.getPoint());

        // We now have the index of the double-clicked cell..




10.1.1    The ListModel interface

abstract interface javax.swing.ListModel

This interface describes a data model that holds a list of items. Method getElementAt() retrieves the item at the given position as an Object instance. Method getSize() returns the number of items in the list. It also contains two methods allowing the registration of ListDataListeners (see below) to be notified of additions, removals, and any changes that occur to this model. Note that this interface leaves the job of specifying how we store and structure the data, as well as how we add, remove, or change an item, completely up to its implementations.

10.1.2 AbstractListModel

abstract class javax.swing.AbstractListModel

This class represents a partial implementation of the ListModel interface. It defines the default event handling functionality, and implements the add/remove ListDataListener methods, as well as methods to fire ListDataEvents (see below) when additions, removals, and changes occur.  The remainder of ListModel, methods getElementAt() and getSize(), must be implemented in any concrete sub-class.

10.1.3  DefaultListModel

class javax.swing.DefaultListModel

This class represents  the concrete default implementation of the ListModel interface. It extends AbstractListModel and uses a java.util.Vector to store its data. Almost all of the methods of this class correspond directly to Vector methods and we will not discuss them here. Familiarity with Vectors implies familiarity with how DefaultListModel works (see API docs).

10.1.4  The ListSelectionModel interface

abstract interface javax.swing.ListSelectionModel

This interface describes the model used for selecting list items. It defines three modes of selection: single selection, single contiguous interval selection, and multiple contiguous interval selection. A selection is defined as an indexed range, or set of ranges, of list elements. The beginning of a selected range (where it originated) is referred to as the anchor, while the last item is referred to as the lead (the anchor can be greater than, less than, or equal to the lead). The lowest selected index is referred to as the minimum, and the highest selected index is referred to as the maximum (regardless of the order in which selection takes place). Each of these indices represents a ListSelectionModel property. The minimum and maximum properties should be -1 when no selection exists, and the anchor and lead maintain their most recent value until a new selection occurs.

To change selection mode we use the setSelectionMode() method, passing it one of the following constants: MULTIPLE_INTERVAL_SELECTION, SINGLE_INTERVAL_SELECTION, and SINGLE_SELECTION. In SINGLE_SELECTION mode only one item can be selected. In SINGLE_INTERVAL_SELECTION mode a contiguous group of items can be selected by selecting an anchor item, holding down the SHIFT key, and choosing a lead item (which can be at a higher or lower index than the anchor). In MULTIPLE_INTERVAL_SELECTION mode any number of items can be selected regardless of their location by holding down the CTRL key and clicking. Multiple selection mode also allows use of SHIFT to select a contiguous interval, however, this has the effect of clearing the current selection.

ListSelectionModel provides several methods for adding, removing, and manipulating ranges of selections. Methods for registering/removing ListSelectionListeners (see below) are provided as well. Each of these methods is self-explanitory in the API docs and we will not describe them in detail here.

JList defines all the methods declared in this interface and simply delegates all traffic to its ListSelectionModel instance. This allows access to selection data without the need to directly communicate with the selection model.

10.1.5  DefaultListSelectionModel

class javax.swing.DefaultListSelectionModel

This class represents the concrete default implementation of the ListSelectionModel interface. It defines methods to fire ListSelectionEvents (see below) when a selection range changes.

10.1.6  The ListCellRenderer interface

abstract interface javax.swing.ListCellRenderer

This interface describes a component used for rendering a list item. We discussed this interface, as well as its default concrete implementation, DefaultListCellRenderer, in the last chapter (see 9.1.4 and 9.1.4). We will show how to construct several custom renderers in the examples that follow.

10.1.7  The ListDataListener interface

abstract interface javax.swing.event.ListDataListener

Defines three methods for dispatching ListDataEvents when list elements are added, removed or changed in the ListModel: intervalAdded(), intervalRemoved(), and contentsChanged().

10.1.8 ListDataEvent

class javax.swing.event.ListDataEvent

This class represents the event delivered when changes occur in a list's ListModel. It includes the source of the event as well as the index of the lowest and highest indexed elements affected by the change. It also includes the type of event that occurred. Three ListDataEvent types are defined as static ints: CONTENTS_CHANGED, INTERVAL_ADDED, and INTERVAL_REMOVED. We can use the getType() method to discover the type of any ListDataEvent.

10.1.9  The ListSelectionListener interface

abstract interface javax.swing.event.ListSelectionListener

This interface describes a listener which listens for changes in a list's ListSelectionModel. It declares the valueChanged() method which accepts a ListSelectionEvent.

10.1.10            ListSelectionEvent

class javax.swing.event.ListSelectionEvent

This class represents an event delivered by ListSelectionModel when changes occur in its selection. It is almost identical to ListDataEvent, except that the indices specified signify where there has been a change in the selection model, rather than the data model.

UI Guideline : Advice on Usage and Design Usage

Much of the UI Guideline advice for List Boxes is similar to that of Comboboxes. Clearly the two things are different and are intended for different purposes. Deciding when to use one or another can be difficult. Our advice is to think about reader output rather than data input. When the reader needs to see a collection of items then a List Box is the correct choice. Use a List Box where there is a collection of data, which may grow dynamically, and for reading purposes it is useful to see the whole collection or as much of the collection as can reasonably be fitted in the available space, e.g. Department Staff <List of Staff Name>.


Like Comboboxes, there are a number of things which affect the usability of a List Box. Beyond more than a few items, they become unusable unless the data is sorted in some logical fashion e.g. alphabetical, numerical. List Boxes are designed to be used with Scroll Pane. It is assumed that the list will most often be too long to display in the available screen space. Using a sensible sorted order for the list, allows the user to predict how much they need to scroll to find what they are looking for.

When a list gets longer, usability is affected again.Once a list gets beyond a couple of hundred items, even when sorted, it becomes very slow for the user to locate specific item in the list. When a list becomes so long, it may be better to consider providing a Search Facility, or grouping the data inside the list using a Tree.

Graphical considerations for List Boxes are much like those for Comboboxes. List Boxes should be aligned to fit attractively into a panel. However, this can be problematic. You must avoid making a List Box which is simply too big for the list items contained e.g. a List Box showing supported file formats such as .gif need only be a few characters long, don't make it big enough to take 50 characters, as it will look unbalanced.

The nature of the list items must also be considered. If you have 50 items in a list where most items are around 20 characters but one item is 50 characters long then should you make the List Box big enough to display the longer one? Well maybe, but for most occasions your display will be unbalanced again. It is probably best to optimise for the more common length, providing the the longer one still has meaning when read in its truncated form. One solution to displaying the whole length of a truncated item is to use the tooltip facility. When the User places the mouse over an item, a tooltip appears with the full length data.

[ Return to Swing (Book) ]

Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color

[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3

[ More in News Section ]

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy