Graphical User Interface Components: Part 1
Graphical User Interface Components: Part 1
Chapter 11
Swing Components
scroll bars
Dialog Boxes
Used by applications to interact with the user Provided by Javas JOptionPane class
Dialog Boxes
Note icon Other icons available
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.
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
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
components
Heavyweight
o o o
components
Tied directly to the local platform AWT components Some Swing components
9
Component
(package java.awt ) Subclass of Object Declares many behaviors and attributes common to GUI components
10
Container
11
JComponent
12
Pluggable look-and-feel
o
Shortcut keys
o
tool tips
13
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
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
16
Object gives information about the event Identifies the event source. Other kinds of objects can also be event sources.
JLabel
Label
o o o
18
Method
o
19
Icon
Can be added to a JLabel with the setIcon method Implemented by class ImageIcon
20
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
JLabel methods
For setting and retrieving the horizontal position of the text displayed in the label 22
Description
23
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
o o
Implement the appropriate interface Be registered as an event listener on the appropriate event source.
25
Event Handling
Events occur when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
26
27
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
Register event listener for event source Implement event-handling method (event handler)
28
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
30
What If ?
When a tree falls in the forest and there's no one present to hear it, does it make a sound?
A program can ignore events If there is no listener for an event, the event is just ignored
31
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
34
Event is dispatched only to listeners of appropriate type Each event type has corresponding eventlistener interface
35
36
JButton
Button
o o
javax.swing.AbstractButton subclasses
Command buttons are created with class JButton Generate ActionEvents when user clicks button
37
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
Program must register object as an action listener on the button (the event source)
o
40
Comments on JButton
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
JToggleButton,
JCheckBox and
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
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
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
JList
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
Multiple-Selection Lists
o o
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
MouseListener MouseMotionListener Listen for MouseEvents Register JFrame to receive mouse events Methods invoked for various mouse events
(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
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
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
Adapter Classes
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
isAltDown()
59
Generated when keys on keyboard are pressed and released Contains virtual key code that represents key
KeyEvent
o
Layout Managers
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
BorderLayout GridLayout
62
FlowLayout
Most basic layout manager GUI components placed in container from left to right Example program, Figure 11.39
o o
63
BorderLayout
(top of container) (bottom of container) (left of container) (right of container) (center of container)
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
Panels
Helps organize components Class JPanel is JComponent subclass May have components (and other panels) added to them
66
Applying Concepts
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
o o o o
Declaration, instantiation of JLabels Container reference, pane Gets handle for contentPane pane layout specified JLabels added
69
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
2.
Code that registers an instance of the event handler class as a listener upon one or more components.
3.