Sei sulla pagina 1di 39

List Boxes

• Usage: To select from a large set of choices that may be exclusive or


non-exclusive
• Description
– A permanently displayed box-shaped control containing a list of attributes
or objects from which:
• A single selection is made
• Multiple selections are made
– The choice may be text or graphics
– Selections are made by using a mouse to point and click
– Capable of being scrolled to view large lists
– No text entry field exists in which to type text

01/01/06 1
More on List Boxes
• Advantages
– Unlimited number of choices
– Reminds users of available options (though not as well as check boxes)
– Box always visible
• Disadvantages
– Consumes screen space
– May require scrolling
– List may change, making it hard to find items
– List may be ordered in an unpredictable way
• Best used for data and choices that are
– Best represented textually
– Not frequently selected
– Not well known, easily learned, or remembered
– Frequently changed
– Large in number
01/01/06 2
List Box Layout
• Box Size
– Should be long enough to display six to eight choices without requiring
scrolling
– If List Box is major component in window, it may be larger
– Must be wide enough to contain the longest possible choice
• Horizontal scrolling should be avoided
• Captions
– Preferred position for the control caption is above the upper-left corner

01/01/06 3
List Boxes in Java
JComponent JList

• User interface containing a collection of similar items from which the


user can make one or more selections.
• In AWT, the similar items are Strings
– Add
– Remove
– Display
– Scroll
• Major revision to List in Swing
– display graphics
– internal representation
– new listeners
• Porting from java.awt.List to javax.swing.JList is not just a matter of
adding a “J”, like you can do with buttons or labels
01/01/06 4
Uses of JList
• Display a simple list of data
• Display and select a simple list of data
• Display and select multiple items from a list of data
• Use your own data model to generate your own data for the JList
• Use your own cell renderer to provide customized graphical output
• Use your own data model and cell renderer to produce complex list
selection models

01/01/06 5
JList
• The best way to look at difference between old and new Lists are:
– List was a container that held a set of Strings, you added and deleted them
from the container
– JList dynamically displays a data model. Built in models handle Vectors
and arrays.
• JList is the simplest of all the data-handling controls, its only purpose
is to take a list of data items and present them in a vertical arrangement
to the user.
• The Basic JList doesn’t even include scrolling, although it does
support it. You need to put it in a JScrollPane
JList list = new JList();
JScrollPane scrolledList = new JScrollPane(list)
• The API has some good examples regarding the use of a JList
– Shows cell rendering
– Custom data model

01/01/06 6
Creating a JList
• Constructors
JList()
• Constructs a JList with an empty model.
JList(ListModel dataModel)
• Construct a JList that displays the elements in the specified, non-null model.
JList(Object[] listData)
• Construct a JList that displays the elements in the specified array.
JList(Vector listData)
• Construct a JList that displays the elements in the specified Vector.
• Methods
– There are many methods within the JList class, but if you will notice, they
are all related to accessing selections and displaying the data, there are no
methods to add or change data in the list.
– Your only choices, as far as JList goes, are to associate the data with it via
the constructor, or completely replace the existing model.
– This is because JList doesn’t manage the data itself, its model does, and
the model is part of a separate class.

01/01/06 7
JList Data
• The empty constructor makes a list with no data at all, but you can set
data later using
public void setModel(ListModel model)
public void setListData(Object[] values);
public void setListData(Vector data)
• JList manages data only if the data presented to it is in the form of a
ListModel
public interface ListModel {
public abstract int getSize();
public abstract Object getElementAt(int Index)
public abstract void addListDataListener(ListDataListener l)
public abstract void removeListDataListener(ListDataListener l)
}
• Swing provides a DefaultListModel that you can use to create a JList,
however it is often easier to use a Vector

01/01/06 8
More on JList
• Neither the array nor the Vector class implements the ListModel
interface, so the JList constructors that accept these data types use an
anonymous class to wrap them and create the appearance of a
ListModel object
• Modifying content
– Both Vectors and arrays can be used to initialize the data model
public JList(final Vector data) {
this (new AbstractListModel() {
public int getSize() {
data.getSize();
}
public Object getElementAt(int index) {
return data.getElementAt(index);
}
}
});
– If you use an array or Vector, you modify them, and the use the
setListData() method to update the JList
01/01/06 9
MyJList1.java

01/01/06 10
Selecting Items in a JList
• Programmatically, at initialization or any time after
public void setSelectedIndex(int index);
public void setSelectedValue(Object value, boolean scroll)
public void setSelectedIndices(int [] indices)
public void setSelectionInterval(int index1, int index2)
public void addSelectionInterval(int index1, int index2)
public void clearSelection();
public void removeSelectionInterval(int index1, int index2)
• In the same way that JList doesn’t manage the data that it displays, it
also doesn’t directly deal with remembering which items are selected
at any time
– It delegates this responsibility to a class implementing the
ListSelectionModel interface
• Multiple selections are allowed depending on the list selection mode
• When you create a JList, the ListSelectionModel you get by default is
in multiple interval selection mode.

01/01/06 11
More on List Selection
• To select a contiguous range of items, click on the item at one end of
the range, then hold down the SHIFT key while clicking on the other
– First item is the anchor of the selection
– Second clicked on is the lead
• To select non-adjacent items, use the CTRL key as you click
• List Selection Events
– To receive notification of a selection, you need to register a
ListSelectionListener using the addListSelctionListener()
method of JList.
• ListSelectionListener interface has only one method
• public abstract void valueChanged(ListSelectionEvent evt)
• ListSelectionEvent
– contains source (JList) of the event
– two indices that indicate a range of values between which a change has
occurred
– flag which indicates the selection is still changing
01/01/06 12
ListSelectionEvent
• Methods to get information
– public Object getSource()
– public int getFirstIndex()
– public int getLastIndex()
– public boolean getValueIsAdjusting()
• Code Example, ListExample2.java

01/01/06 13
More on List Selection
• Most platforms allow a double-click on a list to select. If you do this
with JList you just get two ListSelectionEvents
• JList doesn’t know how to deal with double clicks
• If you want to react to double clicks, you’ll have to create your own
listener
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
JList l = (JList)evt.getSource();
int index = l.locationToIndex(evt.getPoint());
if (index > 0) {
Object value = l.getModel().getElementAt(index);
System.out.println(“Chosen value is “ + value);
}
}
}
}

01/01/06 14
Dynamic JList
• What if you want to show a list box that will be dynamically updated
by the user, rather than selecting static data?
• Code Example MyJList2.java
• Provide:
– Ability to add new text to the list
– Text field to be used to enter new data
– Ability to remove text from the list

• MyJList2a.java enters data on “Enter” key pressed


• MyJList2b.java uses DefaultListModel vs. Vector to store data

01/01/06 15
Custom Data Models
• Default data model
– Uses a Vector internally
– Does not require you to reset the data list within the JList
• Vector and array constructors
– Wraps your data in an abstract class
– It does not copy your data into a new structure (some texts leads you to
believe this)
– It may be expensive to loop through many elements to get the initial width
of the JList
• Custom data model
– Being a lightweight component, JList easily accepts the replacement of its
data model with a custom version.
– To make a custom data model, all you need to do is extend the
AbstractListModel and add the getSize() and getElementAt() methods.

01/01/06 16
Code Example, MyJList3.java

01/01/06 17
Customizing the JList
• Controlling Cell Width
– When a list is first created, it has to walk down all the elements and size
them to get its own width.
• This can be expensive and/or time consuming (e.g. list of 200 fonts)
– You can set a fixed width or height of a cell
• public void setFixedCellWidth(int width)
• public void setFixedCellHeight(int height)
– Since fixed cell size is a function of pixels, how do you come up with
meaningful values
• public void setProtoypeCellValue(Object typicalValue)
• setPrototypeCellValue(“MMMMMMMM”)
• Rendering Components
– Icon - rendered as is
– Any other object – it’s toString() method is rendered

01/01/06 18
List Cell Rendering
• To draw anything other than the default, you need to provide an
implementation of the ListCellRenderer Interface.
• ListCellRenderer Interface has one method
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean
hasFocus)
• You then need to pass this object to the JList using the
setCellRenderer method
• The JList will take the Component returned and render it in the
JList using the Component’s paint() method, making it draw
into a Graphics object that covers part of the JList’s surface.

01/01/06 19
How to create a List Cell Renderer
• Two methods
– The object that implements the rendering interface returns itself to
be rendered
– The object that implements the rendering interface access a different
object which it in turn returns to be rendered
• Code Example, MyJList4.java & CustomCellRenderer.java

01/01/06 20
MyJList4a
• This is the “other” way of doing a custom renderer, make the renderer
return an object to be used when rendering
• Same list as in previous slide
• Different Renderer
– JPanel w/ a JLabel
– Even number of letters in list show up as green cell, “Even “ text
– Odd number of letters show up as red cell “Odd” text

01/01/06 21
Code Explanation, MyJList5.java
• This next example is out of Core Java Foundation Classes
• It is a bit more elaborate, but shows several interesting techniques
• Components to sample program
– First there is a ColorFillIcon class which implements the Icon interface.
This builds a custom Icon (which holds a color) which will be used in the
JList
– Second,there is a ColorChangeAction. The ColorChangeAction is an
implementation of an AbstractAction which effectively holds a string
name and an Icon in one place
– Third, there is a JLabel, extended to implement the ListCellRenderer
interface, that is used to render the ColorChangeAction above
– Finally, there is a JList, which has a double-click mouse listener
implemented to choose a color

01/01/06 22
`

01/01/06 23
Code Example, MyJList6.java &
CustomCellRenderer6.java
• As a final example, we use a JTextArea as a base for a renderer
instead of a JLabel, this lets us get multi-line text into a JList

01/01/06 24
Other JList significant methods
• Setting selection colors
public Color getSelectionForeground()
public void setSelectionForeground(Color color)
public Color getSelectionBackground()
public void setSelectionBackground(Color color)
• Set visible row count
public void setVisibleRowCount(int visibleNumber)
• Setting an item to be visible
public int getFirstVisibleIndex()
public int getLastVisibleIndex()
public void ensureIndexIsVisible(int index)
• Setting the selection mode
public void setSelectionMode(int selectionMode)
– SINGLE_SELECTION
– SINGLE_INTERVAL_SELECTION
– MUTLIPLE_INTERVAL_SELECTION (Default)
• Enable drag and drop
setDragEnabled(boolean)
01/01/06 25
Renderer Hints
• A JLabel is often used as a Cell Renderer for Jlist in many book
examples
• DefaultListCellRenderer is a better choice
– Inherits from JLabel
– Optimized methods for repaint() to aid in drawing
– You can set its background color!

01/01/06 26
Combo Boxes
• Drop down, exclusive List Boxes. Used to select one item from a large
list of mutually exclusive options when screen space is limited
• To select from a large set of choices that is exclusive
• Description
– A single rectangular-shaped control with a small button to the side and an
associated list of options
• The button provides the visual cue that an associated selection box is available
but hidden
– When the button is selected, the larger associated box becomes visible
– Selections are made by using a mouse to point and click
– Capable of being scrolled to view large lists
– A text entry field may exist in which to type text

01/01/06 27
More on Combo Boxes
• Advantages
– Unlimited number of choices
– Reminds users of available options
– Conserves screen space
– Flexible, permitting selection or typed entry
• Disadvantages
– Requires an extra action to display the list of choices
– List may be ordered in an unpredictable way
– Users may have difficulty recalling sufficient information to type entry,
making text box unusable

01/01/06 28
Usage of Combo Boxes
• Best usage
– For selecting values, or setting attributes
– For choices that are mutually exclusive
• List box is good for several possible choices at once
– Where screen space is limited (Radio Buttons not an option)
– Choices best represented textually
– Not frequently selected
– Not well known, easily learned, or remembered
– Frequently changed and Large in number

01/01/06 29
Combo boxes in Java
JComponent JComboBox

• Does not directly inherit from


JTextComponent, but uses one
• Combination of TextField, button
and a list, all in a single
component Pushing button yields...
• By default, the selected text is
displayed in the text field
• Button to the right brings up the
list
• AWT had this, but Swing allows
you to edit the field, display icons
along with or in place of the text.

01/01/06 30
JComboBox methods
• adding and removing elements
add(Object object);
removeItem(Object object)
removeItemAt(int index)
removeAllItems()
• selecting items
setSelectedItem(“Canada”)
setSelectedIndex(int index);
int getSelectedIndex()
Object getSelectedItem()
• Allowing field editing
– comboBox.setEditable(true)

01/01/06 31
JComboBox methods continued
• Other methods
– Programmatically control the pop-up window
showPopup();
hidePopup()
– Control when window places list in scrollable list
setMaximumRowCount(int number)
– Control how items are displayed within List
getRenderer()
setRenderer(ListCellRenderer renderer)
– Listeners
ItemListener(add/remove)
– Fired on change of selection
ActionListener(add/remove)
– Fired when user finished making choice
– ActionCommand
set/get pair

01/01/06 32
Code Example, MyComboBox.java

01/01/06 33
The Combo Box Data Model
• Like JList, the JComboBox uses its own data model
– The ComboBoxModel is derived from the JList ListModel
• Adds methods to set and get a selected item
– May be supplied by constructor
• But…There is no public ComboBoxModel class
• You would have to subclass from DefaultListModel
– No-arg constructor uses its own internal model
– The default ComboBoxModel has several convenience methods that let
you modify the items in the list
public void addItem(Object item)
public void insertItemAt(Object item, in index)
public void removeItem(Object item)
public void removeItemAt(int index)
– Same rules of custom rendering apply…If Objects are Icons, they are
graphically rendered, otherwise the toString() method is used unless you
use the setRenderer() method
• The same custom renderer that works for JList also will work for the combo
box
01/01/06 34
Code Example, MyComboBox2.java
• A more complex example, showing non text options
and different input modes

01/01/06 35
JComboBox and advanced controls
• Another way to navigate a combo box would be to type in the first
letter, and have that selection be made
– This feature is already supported within the JComboBox, as long as it is
not editable
– Limited to a single letter
– Multiple words for a letter are sequentially processed each time the letter
is typed
– Case is ignored
– The search algorithm compares the key pressed to the first character of the
string returned by the components toString() method
• What if we wanted to select our choice as we typed?
– Install a custom key manager by implementing the
JComboBox.KeySelectionManager interface, which only has one method
– public abstract int selectionForKey(char key, ComboBoxModel model)

01/01/06 36
JComboBox additions
• In JDK 1.3, JComboBox configures a renderer for every item it will
display
• For large lists this can take quite a while.
• In JDK 1.4
– public Object getPrototypeDisplayValue()
– The prototype is only checked once instead of every cell

01/01/06 37
JComboBox List Searching Class
• Code Example - MultiKeySelection.java and
ComboBoxSeachExample.java
• This Code implements the following algorithm
– A string containing all of the search characters that have
been typed is created.
– This string is compared to the toString() methods of the
objects in the list
– If a match is found, the index of the match is returned, if no
match -1 is returned leaving the current selection
unchanged.
• Details
– Incoming keystrokes are converted to lowercase. 16 chars
max.
– MultiKeySelection uses the following from JComboBox
• public int getSize()
• public Object getElementAt(int index)

01/01/06 38
JComboBox List Searching Class Continued
• Details continued
– Since it doesn’t have a reference to the JComboBox, it can’t start at
getSelectedIndex(), so it calls getSelectedItem(), converts that to a
string, and then searches the list with that string
– If match is found, the index is returned, otherwise “-1” is returned
– To Clear the search string
• If non-char key is entered, search string is cleared and beep is sounded
• Also, after each key is entered, a Timer is started, if it expires, it is assumed
that the user has given up on the search and the search string discarded.
• Problems
– Works with single words, if space is in word the space bar triggers the
selection of the list

01/01/06 39

Potrebbero piacerti anche