Download as pps, pdf, or txt
Download as pps, pdf, or txt
You are on page 1of 64

Java I--Copyright © 2000 Tom Hunter

Chapter 12
Basic
Graphical User Interface
Components,
Part II

Java I--Copyright © 2000 Tom Hunter


JList

Java I--Copyright © 2000 Tom Hunter


JList
• This class presents a GUI list of selectable objects.

• It supports three selection modes:

—single selection: you choose only one thing at a


time.

—single interval selection: you choose several


things in a row.

—multiple interval selection: you choose several


clumps of items that are not continuous.
This is the default setting.
Java I--Copyright © 2000 Tom Hunter
JList
Recall the Model-View-Controller architecture we learned
last week…

• The JList class delegates the job of showing the list


and handling its events.

• Therefore, the list’s model keeps a list of objects,


—that are rendered in list “cells” by the
(VIEW), a “list cell renderer.”

Java I--Copyright © 2000 Tom Hunter


JList: How the JList is Drawn (Rendered)
View—list cell renderers are instances of:
DefaultListCellRenderer

How the DefaultListCellRenderer handles


various objects:

Object Type… is rendered (drawn) by…

Icon as is

Object with the string returned


from toString()

String as is
Java I--Copyright © 2000 Tom Hunter
JList: How the JList is Drawn (Rendered)
• A JList can display an Icon and a String—but not
both at the same time.

• The DefaultListCellRenderer can only display a


single object at one time.

• If you implement your own custom subclass from the


JList , you can make it do special things.

Java I--Copyright © 2000 Tom Hunter


JList: How the JList is Normally Implemented

• Right out of the box, the JList does not support


scrolling, but—just as with the JTextArea—you can
add it to a JScrollPane object.

• You place the JList inside a JScrollPane , and the


list will scroll.

JScrollPane
JList

Making a JList scroll


Java I--Copyright © 2000 Tom Hunter
How the
JList
Reacts to a
Click

Java I--Copyright © 2000 Tom Hunter


JList: Responding to A User’s Clicks

• A JList displays a series of items from which the user


may choose.

• When the user clicks on an item in the JList, a

ListSelectionEvent occurs.

Java I--Copyright © 2000 Tom Hunter


… need to implement ListSelectionListener

Object[] items = { "item1", "item2", "item3", "item4" );


Instantiate your JList
JList list = new JList( items );
list.setVisibleRowCount( 4 ); Set parameters

list.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
);
ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel.SINGLE_INTERVAL )

list.addListSelectionListener( this );

Register the ListSelectionListener as your listener.


public void valueChanged( ListSelectionEvent e )
{
} Override the inherited abstract method
from the Listener interface, and use the
information contained in the
ListSelectionEvent object.
(Only one method to override)
Java I--Copyright © 2000 Tom Hunter
JList: ListSelectionEvent
• Any complexity that arises in this object comes from the
chance that multiple rows may have been selected.
Object that is changing.
Constructor:
First item in range
ListSelectionEvent( Object source, selected.
int firstIndex,
int lastIndex, If this index is the
boolean isAdjusting same as the first,
); only one item has
been selected.

This indicates that many


rapid changes are
happening in succession,
so don’t necessarily
consider this the last one.
Java I--Copyright © 2000 Tom Hunter
JList: ListSelectionEvent
• In practice, you would use the same getSource() that
you have used for the ActionEvent object.

• Both ActionEvent and ListSelectionEvent


inherit this same

getSource() method from EventObject.

* * * However, you will need to cast this back into a


JList object to really take advantage of the information
it contains. * * *

Java I--Copyright © 2000 Tom Hunter


JList: ListSelectionEvent
• If you wish to see what values in the list were selected
when the ListSelectionEvent was triggered, you
use either of two methods: Returns a single
Object
public Object getSelectedValue()

public Object[] getSelectedValues()


Returns an
array of
Objects

Java I--Copyright © 2000 Tom Hunter


JList: ListSelectionEvent
• In a fully rigorous usage, this is the way a
JList is implemented. Nothing selected.
public void valueChanged( ListSelectionEvent e )
{
if( e.getValueIsAdjusting() ) If the user is still choosing,
return; this allows us to wait.
JList listEvent = (JList) e.getSource(); We cast the event
if( listEvent.isSelectionEmpty() )
{ from a generic object
// This means nothing was selected. into a specific one
else that we can probe.
{
int index = listEvent.getSelectedIndex();
// This returns the location of the single line
// that was selected from the list.
}
} Identify exactly what was selected.

Java I--Copyright © 2000 Tom Hunter


public void valueChanged( ListSelectionEvent e )
{ For this example, we don’t
String s = “”; have to cast it into a
JList object. We can use
if( e.getValueIsAdjusting() )
{
the methods in the
s = “Value is adjusting”; ListSelectionEvent
} object.
else
{
s = “Selection from e.getFirstIndex() +
“to” + e.getLastIndex();
} When you move
showStatus( s ); through a list, this is
} the place you where
you started.

When you’re making a selection,


this is the place where you stopped.
Java I--Copyright © 2000 Tom Hunter
If you’re really only
interested in the
final selection point,
you query
e.getLastIndex()

Java I--Copyright © 2000 Tom Hunter


JList: Fine-Grained Selection Properties
• With a JList, you have many alternative ways to discover
what the user did:

JList Selection Properties


Property Meaning

anchor —the index that most recently began an


interval selection.
lead —the last index of the most recent
selection interval.
maximum —the highest index from the selected items.

minimum —the lowest index from the selected items.


Java I--Copyright © 2000 Tom Hunter
int lead = list.getLeadSelectionIndex(), I clicked on item[0]
min = list.getMinSelectionIndex(),
and it made all the
max = list.getMaxSelectionIndex(),
anchor = list.getAnchorSelectionIndex(); methods return 0.
int[] selected = list.getSelectedIndices();
I clicked on item[2]
and it made all the
methods return 2.

I clicked on item[4],
while I held down the
shift key and it shows:
—the lead as 4,
—anchor as 2 (where
I started), and
—array of selected
indexes shows 2,3,4 as
you see.

This button fires method


list.clearSelection()
It sets all these values to -1.

Java I--Copyright © 2000 Tom Hunter


Under the Hood
with the
JList

Java I--Copyright © 2000 Tom Hunter


JList: How the Work is Delegated
• The JList component delegates three major jobs to
other objects:

 data handling, —to ListModel

 item selection and —to ListSelectionModel

 cell rendering —to ListCellRenderer

All three of these


are interfaces.

Java I--Copyright © 2000 Tom Hunter


import javax.swing.*;
import javax.swing.event.*;
Instantiate an array of any
import java.awt.*; Object. Then you
import java.awt.event.*; instantiate the JList object
public class Test extends JApplet
with your array.
{
public void init()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());

Object[] items = { "item one", "item two",


"item three", "item four",
"item five", "item six",
"item seven", "item eight",
You usually decide
"item nine", "item ten" };
how many rows of the
JList list = new JList( items ); list you want to see at
list.setVisibleRowCount( 7 );
any one time. The
c.add( list ); default visible size is 8
} rows.
}
Java I--Copyright © 2000 Tom Hunter
Remember, when we just add
the JList reference to the
Container, we do not
automatically get scrolling. For
that, you need to add the
JList to a JScrollPane.

Notice, although we specified a


visible limit of 7 rows—we’re
seeing 10. What gives?

The
setVisibleRowCount()
method only takes effect when
the list is in a scroll pane

Java I--Copyright © 2000 Tom Hunter


import javax.swing.*;
import javax.swing.event.*;
Remember, the JList
import java.awt.*; accepts an Object.
import java.awt.event.*;
You can put any object
public class Test extends JApplet in a JList.
{
public void init()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());

Object[] items = { "item one", "item two",


"item three", "item four",
"item five", "item six",
"item seven", "item eight",
"item nine", "item ten" };
JList list = new JList( items );
list.setVisibleRowCount( 7 );
JScrollPane sp = new JScrollPane( list );

c.add( sp );
}
}
Java I--Copyright © 2000 Tom Hunter
JList
• You recall, the JList delegates its labor to other classes
that actually do the work.

—For example, the JList does not manage the


data handling—the references—to the objects
it displays.

—Instead, all instances of JList delegate the


management of the data to an object that
implements the ListModel interface.

Java I--Copyright © 2000 Tom Hunter


JList
• To facilitate this model, you can construct instances of a
JList using the following Constructors:

• public JList( ListModel )

• public JList( Object[] )

• public JList( Vector )

Java I--Copyright © 2000 Tom Hunter


JList
• After you have constructed an instance of the class
JList, you can change what is displayed with the
following:

• public void setModel( ListModel )

• public void setListData( Object[] )

• public void setListData( Vector )

• These methods allow you to change the entire contents of


the list in one motion.

• Changing individual elements is not so easy...


Java I--Copyright © 2000 Tom Hunter
JList
• Since the JList does not maintain its own data, it
cannot help you change individual elements in the list.

• To accomplish that, you have to go to where that data is


stored.

—You have to directly manipulate the list’s model.

—All of these “models” must implement the

ListModel interface.

Java I--Copyright © 2000 Tom Hunter


JList
“This interface defines the methods that components like JList
use to get the value of each cell in a list and the length of the list.”

—Logically the model is a vector.

—Its indexes vary from 0 to


ListDataModel.getSize() - 1.

—Any change to the contents or length of the data model


must be reported to all of the

ListDataListeners—the controllers

Java I--Copyright © 2000 Tom Hunter


Adding or Removing
An Item
from the JList

Java I--Copyright © 2000 Tom Hunter


JList: Changes to the Items in the List
• Whenever you add or remove an item from your
list, that is another type of event. To track that
event, you use the object

ListDataListener

Java I--Copyright © 2000 Tom Hunter


JList: Registering a Listener For Changes to the List
• If you want to change an item in a JList, you have to get
its model, and go through the interface

ListDataListener

—Methods the implementing classes must override:

public abstract void addListDataListener( ListDataListener )

public abstract void removeListDataListener( ListDataListener )

—Classes that implement this interface are notified


when the contents of the list changes.
This is the equivalent of the method
addActionListener
Java I--Copyright © 2000 Tom Hunter
JList: ListDataListener
• One of the three methods defined by the
ListDataListener interface class is invoked whenever
data associated with a list is modified.
—Methods the implementing classes must override:

public abstract void contentsChanged( ListDataEvent )

public abstract void intervalAdded( ListDataEvent )

public abstract void intervalRemoved( ListDataEvent )

—If just one item is changed, the first method is called.


—When an “interval” or several contiguous objects in
the list are added, either of the last two
methods are called.
Java I--Copyright © 2000 Tom Hunter
JList: ListDataEvent
• This event object has three constants that define the change
that occurred.
public static final int CONTENTS_CHANGED

public static final int INTERVAL_ADDED

public static final int INTERVAL_REMOVED

Source of the event


• Constructors:
public ListDataEvent( Object source, int type, int index(), int index1 )

Type of the event— Beginning and ending


using the constants indexes of the items that
above. were changed.

Java I--Copyright © 2000 Tom Hunter


JList: Getting the Size—Number of Items in the List
• This method will tell you the number of rows or items in the
list.

public abstract int getSize()

Java I--Copyright © 2000 Tom Hunter


JList: Getting a Reference to a Specific Object in the
List
• This method will give you a reference to a specific
Object in the list.

public abstract Object getElementAt()

Java I--Copyright © 2000 Tom Hunter


JComboBox

Java I--Copyright © 2000 Tom Hunter


JComboBox: Similarities to JList
• A JComboBox gets its name because it is a combination
of an editable area and a drop-down list of selectable
items.

• In other words, a JComboBox is a more complex


JList.

• Because both display a list of items, they both have


models that extend the ListModel interface.

• Likewise, both are components that that render list cells


by implementing the ListCellRenderer interface.

Java I--Copyright © 2000 Tom Hunter


JComboBox
• However, there are differences:
—List cells are not editable

—but Combo Boxes can be given an editor.

The JComboBox component delegates editing

to an object that

implements the ComboBoxEditor interface.

Java I--Copyright © 2000 Tom Hunter


JComboBox
• More differences:

—Lists support three selection modes, and delegate


selection control responsibilities to an object
that implements the
ListSelectionModel interface.

—Combo Boxes can only have


one item selected at one time.

—Selection is handled by combo box models.

Java I--Copyright © 2000 Tom Hunter


JComboBox
• More differences:

—On the other hand, combo boxes support


Key Selection, where a key press can select
an item.

—List boxes do not support Key Selection.

Java I--Copyright © 2000 Tom Hunter


JComboBox: Comparison of Delegate Data Types
Delegate JList JComboBox

Model ListModel ComboBoxModel

Remember, This is an interface that


under the extends the
AbstractListModel
Model-View-
interface. This is also an
Controller
interface, and it
architecture, addListDataListener() extends the
the Model getElementAt( int Index )
getSize() ListModel
takes care of removeListDataListener() interface.
how the data
is stored.
Object getSelectedItem()

setSelectedItem(Object item)
Java I--Copyright © 2000 Tom Hunter
JComboBox: Comparison of Delegate Data Types
Delegate JList JComboBox

Model ListModel ComboBoxModel

Renderer ListCellRenderer ListCellRenderer

This is an interface, and it has a single method. The


return value of this one method returns a
Component that will display anything that
implements the interface, whether that is a
ListModel or a ComboBoxModel.

Java I--Copyright © 2000 Tom Hunter


JComboBox: Comparison of Delegate Data Types
Delegate JList JComboBox

Model ListModel ComboBoxModel

Renderer ListCellRenderer ListCellRenderer

SelectionModel DefaultListSelectionModel —

KeySelectionManager — JComboBox,
DefaultKeySelectionManager

Combo boxes allow items to be selected with a


Remember, the key press. If a key is pressed when the box has
default is multiple focus, a search is initiated for a match between
interval selection. the key and the item in the list.
If there is a hit, the item is selected.
A hit is when the first letter of the list string
matches.
Java I--Copyright © 2000 Tom Hunter
JComboBox: Additional Differences
• Recall, the JList class does not provide methods for
adding, inserting or removing items from the list directly.

—After the JList is constructed, the only way to


modify list data after it has been constructed
is with the:

JList.setListData() method.

—This method permits all of the list items to be


specified at once.

Java I--Copyright © 2000 Tom Hunter


JComboBox: Additional Differences
• The JComboBox is the opposite:
—It is made to have items added and removed from
it all day long.
—But the only way to reset all of the data at once
for a combo box is using the method:

JComboBox.setModel( ComboBoxModel )

Don’t forget, this is an


interface that manages
JComboBox’s data.

Java I--Copyright © 2000 Tom Hunter


JComboBox
• Instances of the JComboBox are—by default—not
editable, so you just have to make a simple call to:

JComboBox.setEditable( true )

and you can edit to your heart’s content.


This example is not editable, as
you can see by the gray
background in the JComboBox.
The behavior of these two
variants—editable and not
editable—is significantly
different.

Showing list Editable


Java I--Copyright © 2000 Tom Hunter
Code Necessary for a JComboBox
private JComboBox comboBox = new JComboBox();


comboBox.addItem( “Top” );
comboBox.addItem( “Center” ); This example uses a default constructor.
comboBox.addItem( “Bottom” ); You could also have used:
public JComboBox( ComboBoxModel )
comboBox.setEditable( true );
public JComboBox( Object[] )
public JComboBox( Vector )

comboBox.getEditor().addActionListener( new ActionListener()


{
public void actionPerformed(ActionEvent e)
{
System.out.println("here" + comboBox.getSelectedItem() );
}
}
); This returns the editor used to paint and edit the selected
item in the JComboBox field.
Java I--Copyright © 2000 Tom Hunter
JComboBox:
Classic Event
Handling

Java I--Copyright © 2000 Tom Hunter


JComboBox: Classic Event Handling
• The most common way you will use a JComboBox is
for making another object react to the choices expressed
by the user.

• For this purpose, you implement the

ItemListener interface.

Java I--Copyright © 2000 Tom Hunter


String[] numbers = { ‘one’, ‘two’, ‘three’, ‘four’ };

JComboBox cb = new JComboBox( numbers );


cb.setMaximumRowCount( 3 );
cb.addItemListener( new Itemlistener()
{
public void itemStateChanged( ItemEvent e )
{
someJLabel.setText( numbers[ cb.getSelectedIndex() ] );
}
}
);

cb.getSelectedIndex()
• This method returns an int, which becomes a subscript
for the array, which returns a String, which becomes the
text.
Java I--Copyright © 2000 Tom Hunter
JComboBox: Classic Event Handling
• Event handling in a JComboBox is tricky for several
reasons.
—When their selected item changes—either by
being selected, or by having them be edited—
every JComboBox fires two events.

1.) For deselecting the previous item.


2.) For selecting the current item.

Also, whenever an item event is fired, an


action event is also fired right away.

Java I--Copyright © 2000 Tom Hunter


JComboBox:
Combo Box Editors

Java I--Copyright © 2000 Tom Hunter


JComboBox: Combo Box Editors
• Because Combo Boxes can be edited, they can fire
ActionEvents that you can track with an
ActionListener.

• In fact, whenever the currently displayed value is edited,


the combo box fires an action event.

Java I--Copyright © 2000 Tom Hunter


public class Test extends JApplet
{
private JComboBox comboBox = new JComboBox();
private ComboBoxEditor editor = comboBox.getEditor();

public void init()


This is an interface, it has
{
Container c = getContentPane(); method getItem(),
comboBox.setEditable(true); which returns an
comboBox.addItem("Top"); Object.
comboBox.addItem("Center");
comboBox.addItem("Bottom");

c.setLayout(new FlowLayout());
c.add(comboBox);

editor.addActionListener( new ActionListener()


{
public void actionPerformed(ActionEvent e)
{
String s = (String) editor.getItem();
showStatus("Item Edited: " + s);
}
Once we get an Object
}); out of the editor,
we cast it}into type String, and discover
}
what the edit was that triggered the event.
Java I--Copyright © 2000 Tom Hunter
JComboBox: Combo Box Editors
• As you might imagine, this is a highly customizable
component.

Java I--Copyright © 2000 Tom Hunter


JTextArea

Java I--Copyright © 2000 Tom Hunter


JTextArea
• This familiar component can display multiple lines.

• Must be a single font, single color.

• This is basic in its function. For complex abilities, choose


the JEditorPane and JTextPane.

• Does not implement scrolling by itself.

• You can specify its word wrapping behavior.

JTextArea txt = new JTextArea();


txt.setLineWrap( true );
Java I--Copyright © 2000 Tom Hunter
JTextArea
• Properties maintained by the JTextArea:
—columns: int—the number of columns displayed
—line count: int—the number of lines of text
contained in the text area.
—line wrap: boolean—determines whether or not
lines of text are wrapped at the
right edge of a text area.
—rows: int—the number of lines of text displayed
in a text area.
—tabSize: int—number of characters inserted when
the tab key is pressed.
—wrapStyleWord: boolean—when true, causes
words to be wrapped on words.
If false, wrap is on characters.
Java I--Copyright © 2000 Tom Hunter
JEditorPane

Java I--Copyright © 2000 Tom Hunter


JEditorPane
• Just like JTextAreas, these are capable of displaying
multiple lines of editable text.

• Unlike text areas, JEditorPanes can display HTML and


RTF formats.
JEditorPane editor = new JEditorPane();
editor.setPage( url );

Java I--Copyright © 2000 Tom Hunter


JEditorPane
• Hyperlink events are fired when a mouse pressed event
occurs over a hyperlink in an editor pane that is displaying
an HTML document.

• Naturally, Swing defines a HyperLinkListener interface


and HyperLinkEvent class that permits hyperlink events to
be handled.

public abstract void

hyperlinkUpdate( HyperlinkEvent h )

Java I--Copyright © 2000 Tom Hunter


JEditorPane
• The HyperlinkEvent object offers the following methods:

HyperlinkEvent:

—public String getDescription()

—public HyperlinkEvent.EventType
getEventType()

—public URL getURL()

Java I--Copyright © 2000 Tom Hunter


JEditorPane editor = new JEditorPane();

editor.addHyperlinkListener(
new HyperlinkListener()
{
public void hyperlinkUpadate( HyperLinkEvent e )
{
editor.setPane( e.getURL() );
}
}
);

Java I--Copyright © 2000 Tom Hunter

You might also like