64
Java I--Copyright © 2000 Tom Hunter

Graphical User Interface(GUI) Components part-2

Embed Size (px)

Citation preview

Page 1: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

Page 2: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

Chapter 12Basic

Graphical User Interface Components,

Part II

Page 3: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

JList

Page 4: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• This class presents a GUI list of selectable objects.

• It supports three selection modes:

—single selection: you choose only one thing at atime.

—single intervalinterval selection: you choose severalthings in a row.

—multiplemultiple interval selection: you choose severalclumps of items that are not continuous.This is the default setting.

JList

Page 5: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

JList

Page 6: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

JList: How the JList is Drawn (Rendered)

Page 7: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

JList: How the JList is Drawn (Rendered)

Page 8: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

JList: How the JList is Normally Implemented

JScrollPaneJList

Making a JList scroll

Page 9: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

How the JList

Reacts to a Click

Page 10: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

JList: Responding to A User’s Clicks

Page 11: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

JList list = new JList( items );list.setVisibleRowCount( 4 );

list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );

list.addListSelectionListener( this );

… need to implement ListSelectionListener

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

Instantiate your JList

Set parameters

Register the ListSelectionListener as your listener.

Override the inherited abstract method from the Listener interface, and use the information contained in the ListSelectionEvent object. (Only one method to override)

ListSelectionModel.SINGLE_INTERVAL );ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

public void valueChanged( ListSelectionEvent e ){}

Page 12: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• Any complexity that arises in this object comes from the chance that multiple rows may have been selected.

Constructor:

ListSelectionEvent( Object source, int firstIndex, int lastIndex, boolean isAdjusting);

JList: ListSelectionEvent

Object that is changing.

First item in range selected.

If this index is the 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.

Page 13: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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. * * *

JList: ListSelectionEvent

Page 14: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• If you wish to see what values in the list were selected when the ListSelectionEvent was triggered, you use either of two methods:

public Object getSelectedValue()

public Object[] getSelectedValues()

JList: ListSelectionEvent

Returns a single Object

Returns an array of Objects

Page 15: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• In a fully rigorous usage, this is the way a JList is implemented.

JList: ListSelectionEvent

public void valueChanged( ListSelectionEvent e ){ if( e.getValueIsAdjusting() )

return;

JList listEvent = (JList) e.getSource(); if( listEvent.isSelectionEmpty() ) {

// This means nothing was selected. else { int index = listEvent.getSelectedIndex();

// This returns the location of the single line// that was selected from the list.

}}

If the user is still choosing, this allows us to wait.

We cast the event from a generic object into a specific one that we can probe.

Nothing selected.

Identify exactly what was selected.

Page 16: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

public void valueChanged( ListSelectionEvent e ){ String s = “”;

if( e.getValueIsAdjusting() ) {

s = “Value is adjusting”; } else { s = “Selection from e.getFirstIndex() +

“to” + e.getLastIndex(); } showStatus( s );}

For this example, we don’t have to cast it into a

JList object. We can use the methods in the

ListSelectionEvent object.

When you move through a list, this is the place you where you started.

When you’re making a selection,this is the place where you stopped.

Page 17: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

If you’re really only interested in the

final selection point, you query

e.getLastIndex()

Page 18: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• With a JList, you have many alternative ways to discover what the user did:

JList Selection PropertiesProperty Meaning

anchor —the index that most recently began aninterval selection.

lead —the last index of the most recentselection interval.

maximum —the highest index from the selected items.

minimum —the lowest index from the selected items.

JList: Fine-Grained Selection Properties

Page 19: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

int lead = list.getLeadSelectionIndex(), min = list.getMinSelectionIndex(), max = list.getMaxSelectionIndex(), anchor = list.getAnchorSelectionIndex(); int[] selected = list.getSelectedIndices();

I clicked on item[0] and it made all the methods return 0.

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.

Page 20: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

Under the Hood with theJList

Page 21: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• The JList component delegates three major jobs to other objects:

data handling,

item selection and

cell rendering

JList: How the Work is Delegated

—to ListModel

—to ListSelectionModel

—to ListCellRenderer

All three of these are interfacesinterfaces.

Page 22: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

import javax.swing.*;import javax.swing.event.*;import java.awt.*;import java.awt.event.*;

public class Test extends JApplet{

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 );

c.add( list );}

}

Instantiate an array of any Object. Then you instantiate the JList object with your array.

You usually decide how many rows of the list you want to see at any one time. The default visible size is 8 rows.

Page 23: Graphical User Interface(GUI) Components  part-2

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

Page 24: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

import javax.swing.*;import javax.swing.event.*;import java.awt.*;import java.awt.event.*;

public class Test extends JApplet{

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 );}

}

Remember, the JList accepts an Object.

You can put any object in a JList.

Page 25: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• You recall, the JList delegates its labor to other classes that actually do the work.

—For example, the JList does not manage thedata handling—the references—to the objectsit displays.

—Instead, all instances of JList delegate the management of the data to an object thatimplements the ListModel interfaceinterface.

JList

Page 26: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

• public JList( ListModel )

• public JList( Object[] )

• public JList( Vector )

JList

Page 27: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

JList

Page 28: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

JList

Page 29: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

“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 modelmust be reported to all of the

ListDataListeners—the controllerscontrollers

JList

Page 30: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

Adding or Removing An Item

from the JList

Page 31: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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

JList: Changes to the Items in the List

Page 32: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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 notifiedwhen the contents of the list changes.

JList: Registering a Listener For Changes to the List

This is the equivalent of the method addActionListener

Page 33: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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 inthe list are added, either of the last two methods are called.

JList: ListDataListener

Page 34: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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

• Constructors:

public ListDataEvent( Object source, int type, int index(), int index1 )

JList: ListDataEvent

Source of the event

Type of the event—using the constants above.

Beginning and ending indexes of the items that were changed.

Page 35: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• This method will tell you the number of rows or items in the list.

public abstract int getSize()

JList: Getting the Size—Number of Items in the List

Page 36: Graphical User Interface(GUI) Components  part-2

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()

Page 37: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

JComboBox

Page 38: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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 interfaceinterface.

• Likewise, both are components that that render list cells by implementing the ListCellRenderer interfaceinterface.

JComboBox: Similarities to JList

Page 39: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

—but Combo Boxes can be given an editor.

JComboBox

The JComboBox component delegates editing

to an object that

implements the ComboBoxEditor interfaceinterface.

Page 40: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• More differences:

—Lists support three selection modes, and delegateselection control responsibilities to an objectthat implements theListSelectionModel interfaceinterface.

—Combo Boxes can only have one item selected at one time.

—Selection is handled by combo box models.

JComboBox

Page 41: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• More differences:

—On the other hand, combo boxes support Key Selection, where a key press can selectan item.

—List boxes do not supportdo not support Key Selection.

JComboBox

Page 42: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

Delegate JList JComboBox

JComboBox: Comparison of Delegate Data Types

Model ListModel ComboBoxModel

Remember, under the Model-View-Controller architecture, the Model takes care of how the data is stored.

This is also an interfaceinterface, and it extends the ListModel interfaceinterface.

This is an interfaceinterface that extends the AbstractListModel interfaceinterface.

Object getSelectedItem()

setSelectedItem(Object item)

addListDataListener()getElementAt( int Index )getSize()removeListDataListener()

Page 43: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

Delegate JList JComboBox

JComboBox: Comparison of Delegate Data Types

Model ListModel ComboBoxModel

Renderer ListCellRenderer ListCellRenderer

This is an interfaceinterface, 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.

Page 44: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

Delegate JList JComboBox

JComboBox: Comparison of Delegate Data Types

Model ListModel ComboBoxModel

Renderer ListCellRenderer ListCellRenderer

SelectionModel DefaultListSelectionModel —

KeySelectionManager — JComboBox, DefaultKeySelectionManager

Remember, the default is multiple interval selection.

Combo boxes allow items to be selected with a key press. If a key is pressed when the box has focus, a search is initiated for a match between

the key and the item in the list. If there is a hithit, the item is selected.

A hithit is when the first letter of the list string matches.

Page 45: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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 tomodify list data after it has been constructedis with the:

JList.setListData() method.

—This method permits all of the list items to bespecified at once.

JComboBox: Additional Differences

Page 46: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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 )

JComboBox: Additional Differences

Don’t forget, this is an interfaceinterface that manages JComboBox’s data.

Page 47: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

JComboBox

Showing list

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.

Editable

Page 48: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

Code Necessary for a JComboBoxprivate JComboBox comboBox = new JComboBox();

…comboBox.addItem( “Top” );comboBox.addItem( “Center” );comboBox.addItem( “Bottom” );

comboBox.setEditable( true );

comboBox.getEditor().addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e) {

System.out.println("here" + comboBox.getSelectedItem() ); }}

);

This example uses a default constructor.You could also have used:public JComboBox( ComboBoxModel )public JComboBox( Object[] )public JComboBox( Vector )

This returns the editor used to paint and edit the selected item in the JComboBox field.

Page 49: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

JComboBox:Classic Event

Handling

Page 50: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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 interfaceinterface.

JComboBox: Classic Event Handling

Page 51: Graphical User Interface(GUI) Components  part-2

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.

Page 52: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• Event handling in a JComboBox is tricky for several reasons.

—When their selected item changes—either bybeing 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 alsoalso fired right away.

JComboBox: Classic Event Handling

Page 53: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

JComboBox:Combo Box Editors

Page 54: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

JComboBox: Combo Box Editors

Page 55: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

public void init() {

Container c = getContentPane();comboBox.setEditable(true);comboBox.addItem("Top");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);

}});

}}

This is an interfaceinterface, it has method getItem(), which returns an Object.

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.

Page 56: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• As you might imagine, this is a highly customizable component.

JComboBox: Combo Box Editors

Page 57: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

JTextArea

Page 58: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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 );

JTextArea

Page 59: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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 displayedin a text area.

—tabSize: int—number of characters inserted when the tab key is pressed.

—wrapStyleWord:boolean—when true, causeswords to be wrapped on words. If false, wrap is on characters.

JTextArea

Page 60: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

JEditorPane

Page 61: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

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

• Unlike text areas, JEditorPanes can display HTML and RTF formats.

JEditorPane

JEditorPane editor = new JEditorPane();

editor.setPage( url );

Page 62: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• 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 )

JEditorPane

Page 63: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

• The HyperlinkEvent object offers the following methods:

HyperlinkEvent:

—public String getDescription()

—public HyperlinkEvent.EventTypegetEventType()

—public URL getURL()

JEditorPane

Page 64: Graphical User Interface(GUI) Components  part-2

Java I--Copyright © 2000 Tom Hunter

JEditorPane editor = new JEditorPane();

editor.addHyperlinkListener( new HyperlinkListener(){ public void hyperlinkUpadate( HyperLinkEvent e ) {

editor.setPane( e.getURL() ); }

} );