Graphical User Interface Components: Part 1
Chapter 11
What You Will Learn
Swing Components
Event handling Mouse event handling
2
Graphical User Interface (GUI)
Gives program distinctive look and feel Provides users with basic level of familiarity Built from GUI components (controls, widgets, etc.)
User interacts with GUI component via mouse, keyboard, etc
Check out this visual index of components
3
Netscape Window With GUI Components
button menus menu bar combo box
scroll bars
Dialog Boxes
Used by applications to interact with the user Provided by Javas JOptionPane class
Contains input dialogs and message dialogs
Title TitleBar Bar Prompt Promptto to user user which whichallows allows user userinput input
View example program, Figure 11.2 Text Textfield field
When Whenuser userclicks clicksOK, OK, dialog dialogbox boxdismissed dismissed
Dialog Boxes
Note icon Other icons available
Message dialog type
ERROR_MESSAGE INFORMATION_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE
Icon
Description
A dialog that indicates an error to the user. A dialog with an informational message to the user. A dialog warning the user of a potential problem.
PLAIN_MESSAGE
A dialog that poses a question to the user. This dialog normally requires a response, such as clicking a Yes or a No button. no icon A dialog that contains a message, but no icon.
Some Basic GUI Components
Component
JLabel JTextField JButton JCheckBox JComboBox JList JPanel
Description
Displays uneditable text or icons. Enables user to enter data from the keyboard. Can also be used to display editable or uneditable text. Triggers an event when clicked with the mouse. Specifies an option that can be selected or not selected. Provides a drop-down list of items from which the user can make a selection by clicking an item or possibly by typing into the box. Provides a list of items from which the user can make a selection by clicking on any item in the list. Multiple elements can be selected. Provides an area in which components can be placed and organized. Can also be used as a drawing area for graphics.
Overview
Swing GUI components
o o o
Declared in package javax.swing Most are pure Java components Part of the Java Foundation Classes (JFC) Precursor to Swing Declared in package java.awt Does not provide consistent, cross-platform lookand-feel
8
Abstract Window Toolkit (AWT)
o o o
Lightweight vs. Heavyweight
Lightweight
o
components
Not tied directly to GUI components supported by underlying platform
Heavyweight
o o o
components
Tied directly to the local platform AWT components Some Swing components
9
Superclasses of Swings Lightweight GUI Components
Class
o o o
Component
(package java.awt ) Subclass of Object Declares many behaviors and attributes common to GUI components
10
Superclasses of Swings Lightweight GUI Components
Class
o o o
Container
(package java.awt ) Subclass of Component Organizes Component s
11
Superclasses of Swings Lightweight GUI Components
Class
o o o
JComponent
(package javax.swing ) Subclass of Container Superclass of all lightweight Swing components
12
Common Lightweight Component Features
Pluggable look-and-feel
o
customize the appearance of components mnemonics
Shortcut keys
o
Common event-handling capabilities Brief description of components purpose
tool tips
13
Support for localization
Displaying Text and Images in a Window
Class
o o o
JFrame
Most windows are an instance or subclass of this class Provides title bar Provides min, max, close buttons Text instructions or information stating the purpose of each component Created with class JLabel 14
Label
o o
Three Parts of a GUI Application
1. 2. 3.
Components that make up the Graphical User Interface Listeners that receive the events and respond to them Application code that does useful work for the user
15
Events Generated by Swing Components
Act that results in the event User clicks a button, presses Return while typing in a text field, or chooses a menu item User closes a frame (main window) User presses a mouse button while the cursor is over a component User moves the mouse over a component Component becomes visible Component gets the keyboard focus Table or list selection changes Listener type
ActionListener WindowListener MouseListener MouseMotionListener ComponentListener FocusListener ListSelectionListener
16
Events Generated by Swing Components
Each event is represented by an object
o o
Object gives information about the event Identifies the event source. Other kinds of objects can also be event sources.
Event sources are typically components,
o
Each event source can have multiple listeners registered on it.
o
Conversely, a single listener can register with multiple event sources.
17
JLabel
Label
o o o
Provide text on GUI Defined with class JLabel Can display:
Single line of read-only text Image Text and image
View Figure 11.6
o
Note uses of the JLabel Class
18
Creating and Attaching label1
Method
o
setToolTipText of class JComponent
Specifies the tool tip
Method
o
add of class Container
Adds a component to a container
19
Creating and Attaching label2
Interface
o o
Icon
Can be added to a JLabel with the setIcon method Implemented by class ImageIcon
20
Creating and Attaching label2
Interface
o
SwingConstants
Declares a set of common integer constants such as those used to set the alignment of components Can be used with methods setHorizontalAlignment and setVerticalAlignment
21
Creating and Attaching label3
Other
o o
JLabel methods
getText and setText
For setting and retrieving the text of a label For setting and retrieving the icon displayed in the label
getIcon and setIcon
getHorizontalTextPosition and setHorizontalTextPosition
For setting and retrieving the horizontal position of the text displayed in the label 22
Some basic GUI Components.
Constant
Horizontal-position constants SwingConstants.LEFT SwingConstants.CENTER SwingConstants.RIGHT Vertical-position constants SwingConstants.TOP SwingConstants.CENTER SwingConstants.BOTTOM Place text at the top. Place text in the center. Place text at the bottom. Place text on the left. Place text in the center. Place text on the right.
Description
23
Other JFrame Methods
setDefaultCloseOperation
o
Dictates how the application reacts when the user clicks the close button Specifies the width and height of the window Determines whether the window is displayed (true ) or not (false )
24
setSize
o
setVisible
o
Event Handling
An event occurs every time the user
o o
Types a character or Pushes a mouse button
Any object can be notified of the event. That object must:
o o
Implement the appropriate interface Be registered as an event listener on the appropriate event source.
25
Event Handling
GUI's are event driven
o o
Events occur when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
Class java.awt.AWTEvent Checkout Sun tutorial on event handling
26
Some Event Classes Of Package java.awt.event
27
Event Handling Model
Three parts
o o o
Event source
GUI component with which user interacts Encapsulates information about event that occurred Receives event object when notified, then responds
Event object
Event listener
Programmer must perform two tasks
o o
Register event listener for event source Implement event-handling method (event handler)
28
Event Listener Object
When a GUI program is running, each action of the user generates an event The following are some types of events:
o o o
Moving the mouse Clicking the mouse on a button Typing some text into a text area
For a program to respond to an event there must be an event listener object in the GUI program that listens to that type of event
29
What is an Event Listener?
An event listener is an object
o
It "listens" for events from a specific GUI component (itself an object)
When an event is generated by the GUI component
o
A method in the listener object is invoked to respond to the event
30
What If ?
When a tree falls in the forest and there's no one present to hear it, does it make a sound?
When there is no event listener for an event
o o
A program can ignore events If there is no listener for an event, the event is just ignored
31
Eventlistener Interfaces Of Package java.awt. event
32
Textfields
JTextField
o
Single-line area in which user can enter text Extends JTextField Hides characters that user enters Illustrates capabilities of textfields Note help on handling number fields
33
JPasswordField
o o
View Figure 11.9, Test Program 11.10
o o
How Event Handling Works
You must register the event handler
o
Through components method addActionListener
34
How Event Handling Works
The component knows to call actionPerformed because
o o
Event is dispatched only to listeners of appropriate type Each event type has corresponding eventlistener interface
Event ID specifies event type that occurred
35
Event Registration for JTextField textField1
36
JButton
Button
o o
Component user clicks to trigger a specific action Several different types
Command buttons Check boxes Toggle buttons Radio buttons
javax.swing.AbstractButton subclasses
Command buttons are created with class JButton Generate ActionEvents when user clicks button
37
Swing Button Hierarchy
38
JButton Example
View, ButtonFrame class, Figure 11.15 Test program, Figure 11.16 Look for
o o o o
Declaration of the buttons Inner class ButtonHandler which does event handling for the button Call to .addActionListener(handler) method registers buttons to receive events The actionPerformed() method
39
Comments on JButton
To detect when user clicks button
o
Program must have an object that implements ActionListener interface
Program must register object as an action listener on the button (the event source)
o
Using the addActionListener method
40
Comments on JButton
When user clicks the button, it fires an action event.
o o
Results in the invocation of the action listener's actionPerformed method The only method in the ActionListener interface Appears when mouse is positioned over a button Added to a JButton with method setRolloverIcon
41
JButtons can have a rollover icon
o o
Buttons That Maintain State
Swing
contains three types of state buttons
JToggleButton,
JCheckBox and
JRadioButton JCheckBox and JRadioButton are subclasses of JToggleButton
42
JCheckBox
Contains
Things to a check box label that appears to right of Things toNote: Note: Declaration check box by default Declarationof ofJCheckBox JCheckBox references references
Generates
o
an ItemEvent
ItemListener CheckBoxHandler CheckBoxHandlerinvokes invokesmethod method o Passed to method itemStateChanges itemStateChanged itemStateChanges Change JTextField font, depending on Change JTextField font, depending on box Method isSelected returns whether check which whichJCheckBox JCheckBoxwas wasselected selected is selected (true) or not (false)
ItemEvent s
View
Instantiation Instantiationof ofJCheckBox JCheckBoxobjects when it isobjects clicked Register RegisterJCheckBox's JCheckBox'sto toreceive receiveevents events from CheckBoxHandler CheckBoxHandler are from handled by an
example class Figure 11.17test Figure 11.18
43
JRadioButton
Has two states selected and unselected Normally appear in a group in which only one radio button can be selected at once o Group maintained by a ButtonGroup object Declares method add to add a JRadioButton to group Usually represents mutually exclusive options View RadioButtonFrame, Figure 11.19Test program, Figure 11.20
44
Demonstration of JRadioButton
When viewing Figure 11.19, look for the following
o o o o o
Declaration of JRadioButton references Group specification Instantiation of JRadioButton objects Registration of JRadioButton's to receive events RadioButtonHandler invokes method itemStateChanged
45
JComboBox
JComboBox
o o
List of items from which user can select Also called a drop-down list Instantiate JComboBox to show three Strings from names array at a time Register JComboBox to receive events ItemListener invokes method itemStateChanged 46
Note features in Figure 11.21
JList
A list is a series of items
o o
User can select one or more items Single-selection vs. multiple-selection Note use of ColorNames array to populate JList Specification of SINGLE_SELECTION Registration of JList to receive events ListSelectionListener invokes method valueChanged Background set according to user choice
47
JList demonstration, Figure 11.23
o o o o o
Multiple-Selection Lists
Multiple-selection list capabilities
o o
Select many items from Jlist Allows continuous range selection
Look for the following in Figure 11.25 Use of ColorNames array
o o
Specification of MULTIPLE_INTERVAL_SELECTION option Use of JButton and JListCopyList method
48
Mouse Events
Create a MouseEvent object Handled by MouseListeners and MouseMotionListeners MouseInputListener combines the two interfaces Interface MouseWheelListener declares method mouseWheelMoved to handle MouseWheelEvents
49
Mouse Event Handling
Event-listener interfaces for mouse events
o o o
MouseListener MouseMotionListener Listen for MouseEvents Register JFrame to receive mouse events Methods invoked for various mouse events
In Figure 11.28 note use of
o o
(Note that program does not seem to perform as advertised when run under ReadyTo !!?)
50
Listener Interfaces
MouseListener and MouseMotionListener interface methods
Methods of interface MouseListener public void mousePressed( MouseEvent event ) Called when a mouse button is pressed while the mouse cursor is on a component. public void mouseClicked( MouseEvent event ) Called when a mouse button is pressed and released while the mouse cursor remains stationary on a component. This event is always preceded by a call to mousePressed. public void mouseReleased( MouseEvent event ) Called when a mouse button is released after being pressed. This event is always preceded by a call to mousePressed and one or more calls to mouseDragged. public void mouseEntered( MouseEvent event ) Called when the mouse cursor enters the bounds of a component.
51
Listener Interfaces
MouseListener and MouseMotionListener interface methods
public void mouseExited( MouseEvent event ) Called when the mouse cursor leaves the bounds of a component. Methods of interface MouseMotionListener public void mouseDragged( MouseEvent event ) Called when the mouse button is pressed while the mouse cursor is on a component and the mouse is moved while the mouse button remains pressed. This event is always preceded by a call to mousePressed. All drag events are sent to the component on which the user began to drag the mouse. public void mouseMoved( MouseEvent event ) Called when the mouse is moved when the mouse cursor is on a component. All move events are sent to the component over which the mouse is currently positioned.
52
Listener Interfaces
Suppose your class directly implements MouseListener,
o o
Then you must implement all five MouseListener methods. Even if you care only about mouse clicks
Methods for those events you don't care about can have empty bodies.
o
Resulting collection of empty method bodies can make code harder to read and maintain
53
Adapter Classes
Solution is to use adapter classes For example, the MouseAdapter class implements the MouseListener interface. An adapter class implements empty versions of all its interface's methods.
54
Adapter Classes
To use an adapter
o o
Create a subclass of it, instead of directly implementing a listener interface. By extending MouseAdapter, your class inherits empty definitions of all five of the methods that MouseListener contains.
55
Adapter Classes
Characteristics of an adapter class
o o o
Implements interface Provides default implementation of each interface method Used when all methods in interface is not needed
Implements interface
ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener 56 WindowListener
Event-adapter class in java.awt.event
ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter
Adapter Classes
Example of use of an adapter class
o
Figure 11.34 , the Painter program Registration of MouseMotionListener to listen for windows mouse-motion events Override method mouseDragged, but not method mouseMoved Store coordinates where mouse was dragged, then repaint JFrame
57
Note
o o o
Extending MouseAdapter
The MouseDetails.java program, Note example, Figure 11.31 Demonstrates
o o
How to determine the number of mouse clicks How to distinguish between different mouse buttons
58
InputEvent Methods
Help distinguish among
o o o
left-, center- and right-mouse-button clicks
Returns true when the user clicks the right mouse button on a mouse with two or three buttons. To simulate a right-mousebutton click on a one-button mouse, the user can hold down the Meta key on the keyboard and click the mouse button. Returns true when the user clicks the middle mouse button on a mouse with three buttons. To simulate a middle-mousebutton click on a one- or two-button mouse, the user can press the Alt key on the keyboard and click the only- or left-mouse button, respectively.
InputEvent method Description
isMetaDown()
isAltDown()
59
Key Event Handling
Interface KeyListener Handles key events
Generated when keys on keyboard are pressed and released Contains virtual key code that represents key
KeyEvent
o
Demonstrated in Figure 11.36
60
Layout Managers
Layout manager capabilities
o o o o o
Provided for arranging GUI components Provide basic layout capabilities Processes layout details Programmer can concentrate on basic look and feel Interface LayoutManager
61
Layout Managers
Layout manager methods
Default for javax.swing.JPanel . Places components sequentially (left to right) in the order they were added. It is also possible to specify the order of the components by using the Container method add, which takes a Component and an integer index position as arguments. Default for JFrames (and other windows). Arranges the components into five areas: NORTH, SOUTH, EAST, WEST and CENTER. Arranges the components into rows and columns.
Layout manager Description
FlowLayout
BorderLayout GridLayout
62
FlowLayout
Most basic layout manager GUI components placed in container from left to right Example program, Figure 11.39
o o
Layout set as FlowLayout Note results as user presses button
63
BorderLayout
Arranges components into five regions
o o o o o
NORTH SOUTH EAST WEST CENTER
(top of container) (bottom of container) (left of container) (right of container) (center of container)
View example, Figure 11.41
64
GridLayout
Divides container into grid of specified row an columns Components are added starting at top-left cell
Proceed left-to-fight until row is full Clicking buttons toggles between different layouts
65
GridLayout demonstration, Figure 11.43
o
Panels
Helps organize components Class JPanel is JComponent subclass May have components (and other panels) added to them
Panel example, Figure 11.45
66
Applying Concepts
Suppose you wish to have a GUI which accomplishes the following
o o
Enter numbers in text boxes Press button to do calculations
67
Step By Step
View code to create the window Note
o o o
Class (program) extends JFrame Constructor sets up window using methods inherited from JFrame Method main()instantiates class object
68
Add the Text Labels
View additional code Note
o o o o
Declaration, instantiation of JLabels Container reference, pane Gets handle for contentPane pane layout specified JLabels added
69
Add the Text Boxes
View next iteration of code for adding the JTextFields Note
o o o
Declaration, instantiation of JTextFields Change grid layout of pane for 2 columns Adding to pane
70
Final Version
View final code version Note
o o
Declaration, instantiation of buttons Declaration, definition, instantiation of action handlers
Different author, does not use inner anonymous classes
Add action handlers to the buttons
Our program never actually calls the action handlers 71
Implement an Event Handler
Every event handler requires three bits of code: 1. Code that specifies that the class either
Implements a listener interface or 2. Extends a class that implements a listener interface. For example: public class MyClass implements ActionListener {
1.
2.
Code that registers an instance of the event handler class as a listener upon one or more components.
For example: someComponent.addActionListener(instanceOfMyClass);
3.
Code that implements the methods in the listener interface.
For example: public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... } 72