chapter11-graphicalcomponents
TRANSCRIPT
-
8/22/2019 Chapter11-GraphicalComponents
1/72
Graphical User
InterfaceComponents: Part 1
Chapter11
-
8/22/2019 Chapter11-GraphicalComponents
2/72
2
What You Will Learn
Swing Components
Event handling
Mouse event handling
-
8/22/2019 Chapter11-GraphicalComponents
3/72
3
Graphical User Interface (GUI)
Gives program distinctive look and feel
Provides users with basic level of familiarity
Built from GUI components (controls,
widgets, etc.)
o User interacts with GUI component via mouse,
keyboard, etc
Check out this visual indexof components
http://java.sun.com/docs/books/tutorial/uiswing/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/components/components.html -
8/22/2019 Chapter11-GraphicalComponents
4/72
4
Netscape Window With GUI
Components
menu barbutton combo boxmenus
scroll bars
-
8/22/2019 Chapter11-GraphicalComponents
5/72
5
Dialog Boxes
Used by applications to interact with the user
Provided by Javas JOptionPane classo Contains input dialogs and message dialogs
View example program, Figure 11.2
Title Bar
Prompt to
user
Text field
which allows
user input
When user clicks OK,
dialog box dismissed
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
6/72
6
Dialog Boxes
Note icon
Other icons availableMessage dialog type Icon Description
ERROR_MESSAGE A dialog that indicates an error to the user.
INFORMATION_MESSAGE A dialog with an informational message to theuser.WARNING_MESSAGE A dialog warning the user of a potentialproblem.
QUESTION_MESSAGE A dialog that poses a question to the user. Thisdialog normally requires a response, such as
clicking aYes or a No button.
PLAIN_MESSAGE no icon
A dialog that contains a message, but no icon.
-
8/22/2019 Chapter11-GraphicalComponents
7/72
7
Some Basic GUI Components
Component Description
JLabel Displays uneditable text or icons.JTextField Enables user to enter data from the keyboard. Can also be used to
display editable or uneditable text.
JButton Triggers an event when clicked with the mouse.JCheckBox Specifies an option that can be selected or not selected.JComboBox 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.
JList Provides a list of items from which the user can make a selection byclicking on any item in the list. Multiple elements can be selected.
JPanel Provides an area in which components can be placed and organized.Can also be used as a drawing area for graphics.
-
8/22/2019 Chapter11-GraphicalComponents
8/72
8
Overview
Swing GUI componentso Declared in package javax.swingo Most are pure Java componentso Part of the Java Foundation Classes (JFC)
Abstract Window Toolkit (AWT)
o Precursor to Swingo Declared in package java.awto Does not provide consistent, cross-platform look-
and-feel
-
8/22/2019 Chapter11-GraphicalComponents
9/72
9
Lightweight
vs. Heavyweight
Lightweight components
o Not tied directly to GUI components supportedby underlying platform
Heavyweight components
o Tied directly to the local platformo AWT components
o Some Swing components
-
8/22/2019 Chapter11-GraphicalComponents
10/72
10
Superclasses of Swings
Lightweight GUI ComponentsClass Component
o (package java.awt)o Subclass ofObjecto Declares many behaviors and attributes common
to GUI components
-
8/22/2019 Chapter11-GraphicalComponents
11/72
11
Superclasses of Swings
Lightweight GUI ComponentsClass Container
o (package java.awt)o Subclass ofComponento Organizes Components
-
8/22/2019 Chapter11-GraphicalComponents
12/72
12
Superclasses of Swings
Lightweight GUI ComponentsClass JComponent
o (package javax.swing)o Subclass ofContainero Superclass of all lightweight Swing components
-
8/22/2019 Chapter11-GraphicalComponents
13/72
13
Common Lightweight Component
Features Pluggable look-and-feel
o customize the appearance of components
Shortcut keyso mnemonics
Common event-handling capabilities
Brief description of components purposeo tool tips
Support for localization
-
8/22/2019 Chapter11-GraphicalComponents
14/72
14
Displaying Text and Images in a
WindowClass JFrame
o Most windows are an instance or subclass of this
classo Provides title bar
o Provides min, max, close buttons
Labelo Text instructions or information stating the
purpose of each component
o Created with class JLabel
-
8/22/2019 Chapter11-GraphicalComponents
15/72
15
Three Parts of a GUI Application
1. Components that make up the Graphical
User Interface
2. Listeners that receive the events andrespond to them
3. Application code that does useful work for
the user
-
8/22/2019 Chapter11-GraphicalComponents
16/72
16
Events Generated by Swing
ComponentsAct that results in the event Listener type
User clicks a button, presses Returnwhile typing in a text field, or chooses a
menu item
ActionListener
User closes a frame (main window) WindowListener
User presses a mouse button while thecursor is over a component
MouseListener
User moves the mouse over acomponent
MouseMotionListener
Component becomes visible ComponentListener
Component gets the keyboard focus FocusListener
Table or list selection changes ListSelectionListener
-
8/22/2019 Chapter11-GraphicalComponents
17/72
17
Events Generated by Swing
Components Each event is represented by an object
o Object gives information about the event
o Identifies the event source.
Event sources are typically components,o Other kinds of objects can also be event sources.
Each event source can have multiple listeners
registered on it.o Conversely, a
single listener canregister withmultiple event sources.
-
8/22/2019 Chapter11-GraphicalComponents
18/72
18
JLabel
Labelo Provide text on GUI
o Defined with class JLabelo Can display:
Single line of read-only text
Image Text and image
View Figure 11.6o
Note uses of the JLabel Class
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
19/72
19
Creating and Attaching label1Method setToolTipText of classJComponent
o Specifies the tool tip
Method add of class Containero Adds a component to a container
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
20/72
20
Creating and Attaching label2Interface Icon
o Can be added to a JLabel with the setIconmethod
o Implemented by class ImageIcon
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
21/72
21
Creating and Attaching label2Interface SwingConstants
o Declares a set of common integer constants
such as those used to set the alignment of
components
o Can be used with methodssetHorizontalAlignment andsetVerticalAlignment
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
22/72
22
Creating and Attaching label3OtherJLabel methods
o getText and setText For setting and retrieving the text of a label
o getIcon and setIcon For setting and retrieving the icon displayed in the
label
o getHorizontalTextPosition andsetHorizontalTextPosition For setting and retrieving the horizontal position of the
text displayed in the label
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
23/72
23
Some basic GUI Components.
Constant Description
Horizontal-position constants
SwingConstants.LEFT Place text on the left.SwingConstants.CENTER Place text in the center.SwingConstants.RIGHT Place text on the right.Vertical-position constantsSwingConstants.TOP
Place text at the top.SwingConstants.CENTER Place text in the center.SwingConstants.BOTTOM Place text at the bottom.
-
8/22/2019 Chapter11-GraphicalComponents
24/72
24
OtherJFrameMethods setDefaultCloseOperation
o Dictates how the application reacts when the
user clicks the close button setSize
o Specifies the width and height of the window
setVisibleo Determines whether the window is displayed
(true) or not (false)
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
25/72
25
Event Handling
An event occurs every time the usero Types a character or
o Pushes a mouse button
Any object can be notified of the event.
That object must:o Implement the appropriate interface
o Be registered as an event listeneron the
appropriate event source.
-
8/22/2019 Chapter11-GraphicalComponents
26/72
26
Event Handling
GUI's are event driveno Events occur when user interacts with GUI
o e.g., moving mouse, pressing button, typing intext field, etc.
Class java.awt.AWTEvent Checkout Sun tutorialon event handling
http://java.sun.com/docs/books/tutorial/uiswing/overview/event.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/overview/event.html -
8/22/2019 Chapter11-GraphicalComponents
27/72
27
Some Event Classes Of Package
java.awt.event
-
8/22/2019 Chapter11-GraphicalComponents
28/72
28
Event Handling Model
Three partso Event source
GUI component with which user interactso Event object
Encapsulates information about event that occurred
o Event listener
Receives event object when notified, then responds Programmer must perform two tasks
o Register event listener for event source
o Implement event-handling method (event handler)
-
8/22/2019 Chapter11-GraphicalComponents
29/72
29
Event Listener Object
When a GUI program is running, each actionof the user generates an event
The following are some types of events:o Moving the mouse
o Clicking the mouse on a button
o Typing some text into a text area
For a program to respond to an event theremust be an event listener object in the GUIprogram that listens to that type of event
-
8/22/2019 Chapter11-GraphicalComponents
30/72
30
What is an Event Listener?
An event listener is an objecto It "listens" for events from a specific GUI
component (itself an object) When an event is generated by the GUI
component
oA method in the listener object is invoked torespond to the event
-
8/22/2019 Chapter11-GraphicalComponents
31/72
31
What If ?
When there is no event listener for an event
oA program can ignore events
o If there is no listener for an event, the event is
just ignored
When a tree falls in
the forest and there's
no one present tohear it, does it make a
sound?
-
8/22/2019 Chapter11-GraphicalComponents
32/72
32
Event-
listenerInterfaces
Of Packagejava.awt.event
-
8/22/2019 Chapter11-GraphicalComponents
33/72
33
Textfields
JTextFieldo Single-line area in which user can enter text
JPasswordFieldo Extends JTextField
o Hides characters that user enters
View Figure 11.9, Test Program 11.10o Illustrates capabilities of textfields
o Note helpon handling number fields
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://java.sun.com/developer/JDCTechTips/2001/tt1120.htmlhttp://java.sun.com/developer/JDCTechTips/2001/tt1120.htmlhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
34/72
34
How Event Handling Works
You must register the event handlero Through components method
addActionListener
-
8/22/2019 Chapter11-GraphicalComponents
35/72
35
How Event Handling Works
The component knows to call
actionPerformedbecause
o Event is dispatched only to listeners ofappropriate type
o Each event type has corresponding event-
listener interface Event ID specifies event type that occurred
-
8/22/2019 Chapter11-GraphicalComponents
36/72
36
Event Registration for
JTextField textField1
-
8/22/2019 Chapter11-GraphicalComponents
37/72
37
JButton
Buttono Component user clicks to trigger a specific action
o Several different types Command buttons Check boxes Toggle buttons
Radio buttonso javax.swing.AbstractButton subclasses
Command buttons are created with class JButton GenerateActionEvents when user clicks button
-
8/22/2019 Chapter11-GraphicalComponents
38/72
38
Swing Button Hierarchy
-
8/22/2019 Chapter11-GraphicalComponents
39/72
39
JButton Example
View, ButtonFrame class, Figure 11.15 Test program, Figure 11.16
Look foro Declaration of the buttons
o Inner class ButtonHandler which does eventhandling for the button
o Call to .addActionListener(handler)method registers buttons to receive events
o The actionPerformed() method
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
40/72
40
Comments on JButton
To detect when user clicks buttono Program must have an object that implements
ActionListener interface
Program must register object as an actionlistener on the button (the event source)o Using the addActionListener method
-
8/22/2019 Chapter11-GraphicalComponents
41/72
41
Comments on JButton
When user clicks the button, it fires an actionevent.o Results in the invocation of the action listener's
actionPerformedmethodo The only method in theActionListener
interface
JButtons can have a rollover iconoAppears when mouse is positioned over a button
oAdded to a JButton with methodsetRolloverIcon
-
8/22/2019 Chapter11-GraphicalComponents
42/72
42
Buttons That Maintain State
Swing contains three types of state buttons
JToggleButton, JCheckBox andJRadioButton
JCheckBox and JRadioButton are
subclasses ofJToggleButton
-
8/22/2019 Chapter11-GraphicalComponents
43/72
43
JCheckBox
Contains a check box label that appears to right of
check box by default
Generates an ItemEvent when it is clickedo ItemEvents are handled by an ItemListenero Passed to method itemStateChanged
Method isSelectedreturns whether check boxis selected (true) or not (false)View example class Figure 11.17test Figure 11.18
Things to Note:
Declaration ofJCheckBoxreferences
Instantiation ofJCheckBox objects
RegisterJCheckBox's to receive eventsfrom CheckBoxHandler
CheckBoxHandler invokes methoditemStateChanges
Change JTextFieldfont, depending on
which JCheckBox was selected
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
44/72
44
JRadioButton
Has two states selected and unselected
Normally appear in a group in which only one radio
button can be selected at onceo 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
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
45/72
45
Demonstration ofJRadioButton
When viewing Figure 11.19, look for the
following
o Declaration ofJRadioButton referenceso Group specification
o Instantiation ofJRadioButton objects
o Registration ofJRadioButton's to receiveevents
o RadioButtonHandler invokes methoditemStateChanged
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
46/72
46
JComboBox
JComboBoxo List of items from which user can select
oAlso called a drop-down list Note features in Figure 11.21
Instantiate JComboBox to show three Strings
from names array at a time RegisterJComboBox to receive events
ItemListener invokes method
itemStateChanged
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
47/72
47
JList
A list is a series of itemso User can select one or more items
oSingle-selection vs. multiple-selection
JList demonstration, Figure 11.23o Note use ofColorNames array to populate JList
o Specification ofSINGLE_SELECTION
o Registration ofJList to receive eventso ListSelectionListener invokes methodvalueChanged
o Background set according to user choice
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
48/72
48
Multiple-Selection Lists
Multiple-selection list capabilitieso Select many items from Jlist
oAllows continuous range selection
Look for the following in Figure 11.25
Use of ColorNames arrayo Specification ofMULTIPLE_INTERVAL_SELECTION
option
o Use ofJButton and JListCopyList method
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
49/72
49
Mouse Events
Create aMouseEvent object
Handled byMouseListeners and
MouseMotionListenersMouseInputListener combines the two
interfaces
InterfaceMouseWheelListener declaresmethodmouseWheelMovedto handleMouseWheelEvents
-
8/22/2019 Chapter11-GraphicalComponents
50/72
50
Mouse Event Handling
Event-listener interfaces for mouse eventsoMouseListener
oMouseMotionListenero Listen forMouseEvents
In Figure 11.28 note use of
o RegisterJFrame to receive mouse eventso Methods invoked for various mouse events
(Note that program does not seem to perform as
advertised when run under ReadyTo !!?)
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
51/72
51
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 acomponent.
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 ormore calls to mouseDragged.
public void mouseEntered( MouseEvent event )Called when the mouse cursor enters the bounds of a component.
-
8/22/2019 Chapter11-GraphicalComponents
52/72
52
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 MouseMotionListenerpublic 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.
-
8/22/2019 Chapter11-GraphicalComponents
53/72
53
Listener Interfaces
Suppose your class directly implements
MouseListener,
o Then you must implement all fiveMouseListener methods.
o Even if you care only about mouse clicks
Methods for those events you don't careabout can have empty bodies.
o Resulting collection of empty method bodies can
make code harder to read and maintain
-
8/22/2019 Chapter11-GraphicalComponents
54/72
54
Adapter Classes
Solution is to use adapter classes
For example, theMouseAdapter class
implements theMouseListener interface.An adapter class implements empty versions
of all its interface's methods.
-
8/22/2019 Chapter11-GraphicalComponents
55/72
55
Adapter Classes
To use an adaptero Create a subclass of it, instead of directly
implementing a listener interface.o By extendingMouseAdapter, your class
inherits empty definitions of all five of the
methods thatMouseListener contains.
-
8/22/2019 Chapter11-GraphicalComponents
56/72
56
Adapter Classes Characteristics of an adapter class
o Implements interface
o Provides default implementation of each interface
methodo Used when all methods in interface is not needed
Event-adapter class in java.awt.event Implements interfaceComponentAdapter ComponentListenerContainerAdapter ContainerListener FocusAdapter FocusListenerKeyAdapter KeyListenerMouseAdapter MouseListenerMouseMotionAdapter MouseMotionListener WindowAdapter WindowListener
-
8/22/2019 Chapter11-GraphicalComponents
57/72
57
Adapter Classes
Example of use of an adapter classo Figure 11.34, the Painter program
Noteo Registration ofMouseMotionListener to
listen for windows mouse-motion events
o Override methodmouseDragged, but notmethodmouseMoved
o Store coordinates where mouse was dragged,
then repaint JFrame
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
58/72
58
ExtendingMouseAdapter
TheMouseDetails.java program,Note example, Figure 11.31
Demonstrateso How to determine the number of mouse clicks
o How to distinguish between different mouse
buttons
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
59/72
59
InputEvent Methods
Help distinguish amongo left-,
o center- and
o right-mouse-button clicks
InputEvent method DescriptionisMetaDown() Returnstrue when the user clicks the right mouse button on a
mouse with two or three buttons. To simulate a right-mouse-
button click on a one-button mouse, the user can hold down the
Meta keyon the keyboard and click the mouse button.
isAltDown() Returns true when the user clicks the middle mouse button ona mouse with three buttons. To simulate a middle-mouse-
button click on a one- or two-button mouse, the user can press
the Altkey on the keyboard and click the only- or left-mouse
button, respectively.
-
8/22/2019 Chapter11-GraphicalComponents
60/72
60
Key Event Handling
Interface KeyListener
Handles key events
o Generated when keys on keyboard are pressedand released
KeyEvent
o Contains virtual key code that represents key Demonstrated in Figure 11.36
http://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htmhttp://www.letu.edu/people/stevearmstrong/cosc2103/lectures/CodeSamplesCh11SimpleGUI/CodeSamplesCh11.htm -
8/22/2019 Chapter11-GraphicalComponents
61/72
61
Layout Managers
Layout manager capabilitieso Provided for arranging GUI components
o Provide basic layout capabilitieso Processes layout details
o Programmer can concentrate on basic look and
feelo Interface LayoutManager
-
8/22/2019 Chapter11-GraphicalComponents
62/72
62
Layout Managers
Layout manager methods
Layout manager Description
FlowLayout 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 methodadd, which takes a Component and an integer index position asarguments.
BorderLayoutDefault for JFrames (and other windows). Arranges the componentsinto five areas: NORTH, SOUTH, EAST, WEST and CENTER.
GridLayout Arranges the components into rows and columns.
-
8/22/2019 Chapter11-GraphicalComponents
63/72
63
FlowLayout
Most basic layout manager
GUI components placed in container from
left to right Example program, Figure 11.39
o Layout set as FlowLayout
o Note results as user presses button
-
8/22/2019 Chapter11-GraphicalComponents
64/72
64
BorderLayout
Arranges components into five regions
o NORTH (top of container)
o SOUTH (bottom of container)o EAST (left of container)
o WEST (right of container)
o CENTER (center of container) View example, Figure 11.41
-
8/22/2019 Chapter11-GraphicalComponents
65/72
65
GridLayout
Divides container into grid of specified row
an columns
Components are added starting at top-leftcell
o Proceed left-to-fight until row is full
GridLayout demonstration, Figure 11.43o Clicking buttons toggles between different
layouts
-
8/22/2019 Chapter11-GraphicalComponents
66/72
66
Panels
Helps organize components
Class JPanel is JComponent subclass
May have components (and other panels)added to them
Panel example, Figure 11.45
-
8/22/2019 Chapter11-GraphicalComponents
67/72
67
Applying Concepts
Suppose you wish to have a GUI which
accomplishes the following
o Enter numbersin text boxes
o Press button
to do
calculations
-
8/22/2019 Chapter11-GraphicalComponents
68/72
68
Step By Step
View code to create the window
Note
o Class (program) extends JFrameo Constructor sets up window using methods
inherited from JFrame
o Methodmain()instantiates class object
-
8/22/2019 Chapter11-GraphicalComponents
69/72
69
Add the Text Labels
View additional code
Note
o Declaration, instantiation ofJLabelso Container reference,pane
Gets handle forcontentPaneo
pane layout specifiedo JLabels added
-
8/22/2019 Chapter11-GraphicalComponents
70/72
70
Add the Text Boxes
View next iteration of code for adding the
JTextFields
Noteo Declaration, instantiation of JTextFields
o Change grid layout of pane for 2 columns
oAdding to pane
-
8/22/2019 Chapter11-GraphicalComponents
71/72
71
Final Version
View final code version Note
o Declaration, instantiation of buttonso Declaration, definition, instantiation of action
handlers Different author, does not use inner anonymous
classesoAdd action handlers to the buttons
Our program never actually calls the actionhandlers
I l t E t H dl
-
8/22/2019 Chapter11-GraphicalComponents
72/72
Implement an Event Handler
Every event handler requires three bits of code:
1. Code that specifies that the class either1. Implements a listener interface or
2. Extends a class that implements a listener interface.
For example:
public class MyClass implements ActionListener {2. Code that registers an instance of the event
handler class as a listener upon one or morecomponents.For example:someComponent.addActionListener(instanceOfMyClass);
3. Code that implements the methods in the listenerinterface.For example:public void actionPerformed(ActionEvent e)