CS 2 - PowerPoint PPT Presentation

1 / 133
About This Presentation
Title:

CS 2

Description:

A top-level container, like a Frame, requires event handlers (covered later) ... Container - a generic class that contains Components ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 134
Provided by: facul56
Category:
Tags: container

less

Transcript and Presenter's Notes

Title: CS 2


1
CS 2
  • Introduction to
  • Object Oriented Programming
  • Chapter 10/12
  • Event Handling GUI

2
CS1322
Learning Objectives Basics of Java Graphics
  • Graphics Principles
  • Containers
  • Components
  • Layouts
  • Events

3
Objective
  • (demo Graphic3)

4
Background
  • As we have already seen, printing to, and reading
    from, a text window is pretty ugly.
  • Java is not intended for text I/O
  • Java was designed for graphical window
    interaction
  • So this should be really easy, right?
  • Well, everything is relative. Java graphics are
    much easier than, for example, C.
  • Moreover, they are completely portable between
    computers.
  • If your program runs on your computer, it will
    run on anything with the same or later release of
    the Java Virtual Machine (JVM)

5
Agenda
Graphical User Interfaces -- overview --
essential elements Containers -- overview --
composition vs. inheritance Components --
examples Layout Managers -- examples
Our Roadmap
6
Agenda
Graphical User Interfaces -- overview --
essential elements Containers -- overview --
composition vs. inheritance Components --
examples Layout Managers -- examples
Our Roadmap
7
Graphical User Interface
  • A Graphical User Interface (GUI) is one variety
    of user interface. .
  • User interacts with objects on the screen
    (icons, buttons, scroll-bars, etc.) via mouse
    clicks or keyboard actions.

Ok
8
GUI Popularity
  • Popularized in 1980s by the Macintosh.
  • Now state of the practice, and not final word in
    UI
  • Intended to replace text-based "command line" and
    "function key" interfaces.
  • Despite similarities, GUIs are typically
    platform-specific (Windows 95/98/NT/1900, MacOS,
    X Windows look-and-feel standards).
  • Some graphical toolkits now provide
    cross-platform APIs. E.g. wxWindows, GTK, Java.

9
Javas GUI Capabilities
Java provides essentially two related toolkits
for making GUIs The Abstract Windowing
Toolkit ("AWT"), and The Java
Foundation Classes ("Swing") Swing is merely an
expanded version of the AWT, and provides greater
control and convenience.
10
Why Two Toolkits in Java?
MFC
AWT, then JFC or "Swing"
Well, its a long story. In short, JFC (swing)
is Suns answer to Microsofts MFC--a detailed
toolkit library.
11
Cautionary Note
  • Java has two flavors of toolkits
  • Swing and
  • AWT.
  • It is not wise to mix AWT and Swing Components.
  • For your first programs, stick with one toolkit
    or the other.
  • Well start off with AWT, and the switch to Swing
    Components.
  • How do you tell them apart?
  • Generally, Swing Components will have a "J" in
    front of the class name

AWT
Swing
12
Keep in Mind
  • We will program graphical elements in source code
    (text).
  • There are drag and drop systems (called visual
    editors) but usually there is an underlying
    text-based system
  • Eventually you need to get down to the text level
  • So we will be directly coding GUIs
  • Java is designed to work across different
    platforms.
  • This poses special challenges
  • As does the very nature of WIMP GUIs (windows,
    icons, menus, and pointing device graphic user
    interface)

13
Steps to GUI Construction
We will learn GUI creation in two steps the
"view", and then the "controls" or event handling.
1.
  • In Java, to create a GUI, you (1)
  • Specify a Container, using . . .
  • a Layout Manager to . . .
  • place Components and/or Containers of
    Components . . . on the screen as desired.

I.e. UI form and appearance
FIRST
LATER
2.
  • In Java, to make a GUI act as the
  • interface for a program, you (2)
  • Design human/computer dialog, using Listeners
    and component-generated events

I.e. UI interaction and behavior
14
Agenda
Graphical User Interfaces -- overview --
essential elements Containers -- overview --
composition vs. inheritance Components --
examples Layout Managers -- examples
Our Roadmap
15
GUI Design Creation
There are three essential constructs in any GUI
Containers -- used to hold items (e.g., the
frame) Components -- the widgets or
interactors (e.g., buttons) LayoutManagers
-- the hidden algorithm used to organize the
components inside the container
offset
offset
16
Pop Quiz (hint)
What are the three basic constructs used in
every GUI?
17
Agenda
Graphical User Interfaces -- overview --
essential elements Containers -- overview --
composition vs. inheritance Components --
examples Layout Managers -- examples
Our Roadmap
18
Containers
STEP 1
Containers are special components that may
contain other components.
Note Containment is not the same as inheritance
extension. A Frame may contain buttons, but
buttons are not subclasses of Frame.
19
Containers
  • A Container is a class that extends from
    java.awt.Container
  • As it turns out, the class "Container" is itself
    a Component.
  • Containers can have
  • Layouts set on them
  • Other components or containers added to them.

Object
Component
Container
20
Example
Lets make a simple Frame. When working
with GUIs, you often have to consult the
API. Note the inheritance structure of your
classes.
21
Example
So far, weve used the API to learn how to make a
Frame. We found constructors for public Frame
() public Frame (String strTitle) Now, how
can we set the size of the Frame? We again
return to the API.
22
Example
The class java.awt.Frame does not contain a
method to set its size. But such a method was
inherited from java.awt.Component
23
Example
Likewise, theres no method in java.awt.Frame to
make the Frame visible. Instead, we find the
method "show()" was inherited from java.awt.Window
24
Hello GUI
import java.awt. public class HelloGUI
public static void main (String arg)
System.out.println ("About to make
GUI") Frame f new Frame ("Hello
GUIs") f.setSize( 200, 200 )
f.show() System.out.println
("Finished making GUI") // main //
class HelloGUI
25
(Demonstration)
26
What?
Our program runs, and the frame never goes away.
When we reach the end of main (as our print
statement indicates) why doesnt the program end?

27
Explanation
When the Java VM created our Frame, it entered
into a kind of infinite loop, waiting for
input and events. (This is common of graphical
toolkits.)
while(true) //get user input // handle
event
Since we didnt write any event handlers, not
even the "window disposal" button will work.
28
Solution
To fix this problem, well have to write some
event handling code. But in order to write some
event handling code, we have to create some
components So, for now, youll just have to
use Ctrl-C to end the program. Once the basics
of GUI construction are covered, well return to
this problem.
29
Agenda
Graphical User Interfaces -- overview --
essential elements Containers -- overview --
composition vs. inheritance Components --
examples Layout Managers -- examples
Our Roadmap
30
Design Idea
We really have two choices when working with
top-level containers
java.awt.Frame
MyGUI
We will implement containers using composition
MyGUI
java.awt.Frame
31
Example
import java.awt. public class
HelloComposition Frame f public
HelloComposition() f new Frame("Composition
Test") f.setSize(200,200)
f.setBackground(Color.red) f.show()
public static void main (String arg)
HelloComposition h new HelloComposition()

32
Container Summary
Creating containers requires careful
study of the API. Watch the inheritance
structure of the classes. A top-level
container, like a Frame, requires event handlers
(covered later). There are many useful methods
for customizing containers. Just look them up in
the API. E.g.
myFrame.setBackground(Color.red)
An inherited method
A class, also in the API
33
Agenda
Graphical User Interfaces -- overview --
essential elements Containers -- overview --
composition vs. inheritance Components --
examples Layout Managers -- examples
Our Roadmap
34
Components
STEP 2
Most interactions in a Java GUI are with
Components. Another generic term for Component
in other GUIs (e.g. X Windows) is
"widget". Different types of components for
different types of interaction (e.g. buttons,
etc.) User interactions with components create
events (thus, allow event-driven programming) As
a rule, a Component cannot have other components
inside Exceptions to rule pop up menus may have
menu items added to them. And Containers are
themselves components due to inheritance.
35
Component Examples
36
Component Examples
Component - generic widget that you can
interact with Button - a widget
that you can press Canvas - a
widget that you can draw on Checkbox -
a widget that is checked or not checked
Choice - an option menu that drops
down Container - a generic class that
contains Components Panel - a
Container to be used inside another
container used to split an
existing window Label - a
single line of read-only text List
- a list of Strings Scrollbar
- a horizontal or vertical scrollbar
TextComponent TextArea - multi-line
editable text TextField -
single-line editable text
37
Components--Examples
  • Canvas
  • typically a drawing surface on which shapes,
    graphs, pictures, etc can be drawn.
  • utilize mouse events and mouse motion events to
    interact with the user to accomplish the drawing
    tasks.
  • TextField
  • a one-line data entry area
  • theoretically infinite in length
  • can generate Key events to indicate that the
    user has typed a key
  • more typically, it generates an Action event
    when the user finishes the data entry and hits
    Return in the TextField.

38
Components--Examples
  • Button
  • simply a clickable component
  • appears as a standard button on whatever
    graphical environment the user happens to be
    running at the time
  • generates an Action event when clicked
  • Label
  • a one-line field of text.
  • user cannot change this text directly program
    changes text with setText( ) method.
  • usually not used to capture events (but could)
  • usually used as a one-way information source to
    provide a message to the user.

39
Joining Components Containers
Containers have a method public void
add (Component c) that allows us to place items
inside. Thus Panel p new Panel() Button
b1 new Button ("Example 1") Button b2 new
Button ("Example 2") p.add(b1)
p.add(b2) In this example, two buttons are
added to the panel.
40
Example
import java.awt. public class HelloComponent
Frame f public HelloComponent() f
new Frame("Component Test")
f.setSize(200,200) f.setBackground
(Color.red) Panel p new Panel()
Button b new Button ("Hello Components")
p.add(b) f.add(p) f.show()
public static void main (String
arg) new HelloComponent()
41
(Demonstration)
42
Agenda
Graphical User Interfaces -- overview --
essential elements Containers -- overview --
composition vs. inheritance Components --
examples Layout Managers -- examples
Our Roadmap
43
Layout Managers
STEP 3
We can now create Components and Containers. But
how can they be organized? We might be tempted
to call methods that set the x, y location of a
component in a container. Consulting the API, we
find some likely methods public void
setLocation(int x, int y) public void
setSize(int width, int height)
44
Layout Managers -- Motivation
  • To arrange items, one could specify the location
    of a Component by specific x and y coordinates.
    The Component class contains the method
    setLocation(int width, int height)
  • Frame f new Frame()
  • f.setSize(500,500)
  • Button myButton new Button ("Click")
  • add(myButton)
  • myButton.setLocation(25, 75)

NOTE Origin 0,0 at top left
Whats wrong with this approach?
Note Buttons x and y coordinate starts from
top left
45
Layout Managers -- Motivation
  • Problems with specifying x, y coordinates for
    Component
  • This becomes tedious for even mildly complex
    GUIs.
  • Addition of more components requires
    recalculation of every components x, y
    coordinate
  • If container resizes (e.g., user expands
    window), calculations have to be redone!
  • Solution
  • Position components based on a percentage of
    available container size. Or create an
    algorithm to place components . . .
  • But Java already does this for you . . .

46
Layout Managers -- AWT Based
  • Java provides several layout managers.
  • We will concentrate here on several of them
  • BorderLayout
  • GridLayout
  • FlowLayout
  • BoxLayout
  • To tell a container which layout manager to use,
    invoke the method
  • setLayout( )
  • and specify a type of layout.
  • For example
  • To specify a BorderLayout
  • setLayout (new BorderLayout())

47
Layout Managers Two General Flavors
  • One can conceptually divide layout managers into
    two types
  • Those that attach constraints to their
    components.
  • Those that do not.
  • What does this mean, "attach constraints"? If
    a manager attaches constraints to a component,
    then information about a components location
    (e.g., compass points) is stored with the object.

48
Border Layout
BorderLayout specifies the arrangement
  • To add components to a BorderLayout, specify the
    position in which the component will reside.
  • Only one component (or container) can go in each
    of the five positions.

49
Border Layout--Example
setLayout (new BorderLayout()) add(new Label
("Hello!"), "North") Canvas myCanvas new
Canvas() // more about Canvas in a moment add
(myCanvas, "Center")
Hello!
a fresh canvas for drawing here
50
Layout Manager No Constraints
  • The second type of LayoutManager does not specify
    constraints for the objects it holds.
  • Examples
  • GridLayout()
  • FlowLayout()
  • Without constraints, you cannot accurately
    predict layout behavior across platforms

51
Layout Manager No Constraints
  • import java.awt.
  • public class FlowTest extends Frame
  • String Labels "Short", "Short", "Long
    Label",
  • "Really Long Label", "Really, really
    long"
  • public FlowTest()
  • this.setSize(400,200)
  • setLayout(new FlowLayout())
  • for (int i 0 i lt Labels.length i)
  • Button temp new Button (Labelsi)
  • add (temp)
  • public static void main (String arg)
  • new FlowTest().show()
  • //class test

52
Layout Manager No Constraints
  • Yields

53
Layout Manager No Constraints
  • And also

54
Demonstration
55
Layout Manager No Constraints
  • Note
  • Since pixels, fonts and insets vary with each
    platform, layout without constraints will vary
    greatly.
  • Lesson
  • Use layout managers without constraints only when
    you have few components, or youve anticipated
    their possible movement.

56
Ulcer Check
Confused by the preceding? Yes, its a lot to
take in. BUT THE POINT IS THAT YOU CAN PLACE
CONTAINERS INSIDE OTHER CONTAINERS, and thereby
create a novel layout. For now, stick with the
simple layouts (e.g., the simple BorderLayout),
and become comfortable with components.
57
Questions?
58
Event Basics
  • Events
  • What is an event?
  • Simple (?) Example
  • Swing Components
  • JFrames
  • JComponents
  • An example
  • Swing Component Design (MVC/UI-Delegate)

59
Events
  • Behind the scenes, the Java runtime environment
    is monitoring many things
  • When any of a number of things happen an event is
    said to occur. Sometimes the terminology is an
    event gets fired"
  • Examples of the types of things that can "fire"
    events
  • Pressing a key on the keyboard
  • Clicking on a component (like a button)
  • Entering a component with the mouse pointer
  • Have a timer "time-out"

60
Events
  • Moving the mouse around any reasonably
    complicated GUI can literally cause hundreds if
    not thousands of events to occur
  • Events will be ignored except for the ones that
    you tell Java that you are interested in doing
    something about
  • Java maintains a data structure of all the events
    that you have decided to handle and looks up
    events and does what you tell it to do.

61
Remember this???
  • import java.awt.
  • public class HelloGUI
  • public static void main (String arg)
  • System.out.println("About to make GUI")
  • Frame f new Frame ("Hello GUIs")
  • f.setSize( 200, 200 )
  • f.show()
  • System.out.println("Finished making
    GUI")
  • // main
  • // class HelloGUI

62
What didn't work???
63
Making it work
  • Determine which event occurs when the "Close the
    Window" button is pressed
  • The API is your friend
  • The lecture notes are your friend
  • Hint In this case it's an event called "Window
    Closing"
  • You decide what class is going to handle this
    event
  • It might be the actual class which has the window
  • It can be any other class
  • Write the method (and class?) that will handle
    the event. When this event occurs, Java is going
    to go to the class that you identify as the event
    handler or Listener. It will look for a method
    called
  • public void windowClosing(WindowEvent e)
  • Java will report an error to you if this class
    doesn't have this method.

64
An Interface
  • // Note found in java.awt.event
  • public interface WindowListener
  • extends EventListener
  • void windowActivated(WindowEvent e)
  • void windowClosed(WindowEvent e)
  • void windowClosing(WindowEvent e)
  • void windowDeactivated(WindowEvent e)
  • void windowDeiconified(WindowEvent e)
  • void windowIconified(WindowEvent e)
  • void windowOpened(WindowEvent e)

65
So we could write a class like this
  • import java.awt.
  • import java.awt.event.
  • public class Handler implements WindowListener
  • public void windowActivated(WindowEvent e)
  • public void windowClosed(WindowEvent e)
  • public void windowClosing(WindowEvent e)
  • Window w e.getWindow()
  • w.setVisible(false)
  • w.dispose()
  • System.exit(0)
  • public void windowDeactivated(WindowEvent e)
  • public void windowDeiconified(WindowEvent e)
  • public void windowIconified(WindowEvent e)
  • public void windowOpened(WindowEvent e)

66
Making it work II
  • Register the listener with Java. That is, tell
    Java which class has the method to run when the
    Window Closing Event occurs.

67
Registration
  • import java.awt.
  • public class HelloGUI
  • public static void main (String arg)
  • Handler h new Handler()
  • System.out.println ("About to make GUI")
  • Frame f new Frame ("Hello GUIs")
  • f.setSize( 200, 200 )
  • f.addWindowListener(h)
  • f.show()
  • System.out.println("Finished making GUI")
  • // main
  • // class HelloGUI

68
Demonstration
69
Diagramatically
Class Pool
class HelloGUI main Frame f Handler
h
class Frame
class Handler
Interface WindowListener
Frame Instance
Handler Instance
70
Key Ideas
  • Determine which event occurs
  • Decide what class is going to handle this event
  • Write the method (and class?) that will handle
    the event.
  • Register the listener with Java.

71
Questions?
  • Very important that you understand this simple
    example to understand the concepts that follow.

72
Potential Points of Confusion
  • What exactly is the listener? Is it the component
    getting clicked on?
  • No, the listener is the object that contains the
    method that Java will call when the event
    happens.
  • You must tell the component getting clicked which
    object that is by registering addWindowListener..
    .
  • As we will see it could be the same object!!!
  • What type of listener do I use?
  • There are only so many
  • See the API
  • Lecture/Instructor/Recitation/TA/etc.
  • Experience!
  • What about all those other window things (e.g.
    windowActivated)
  • We actually did implement them (with empty
    bodies)
  • We said Don't do anything!

73
Events
Here, we review event handling. To understand
how events work in Java, we have to look closely
at how we use GUIs.
When you interact with a GUI, there are many
events taking place each second. Only a few of
these, however, may actually be delivered to
the application.
74
Events
Java uses a delegation event model found in
many other toolkits. Under the delegation model,
components fire events, which can be caught and
acted on by listeners. A listener is linked to a
component through a registration process. The
delegation event model is contrasted to an event
filtration model where all events are delivered
to target components regardless of whether they
asked for them.
75
General Overview
Recall our first consideration of events, where
our first frame would not close, even when the
end of main() was reached.
We explained this behavior by thinking of our
program as entering an infinite loop when the
graphics are shown. This infinite loop is
actually an event-driven cycle, but we can think
of it as a while (true) structure that
periodically polls for user input.
76
The Real Story
We usually think of our program as a
single, linear set of steps being executed. But
something special happens when we create
graphical objects.
77
The Real Story
When Java sees that youve created a GUI, your
program gets a second set of linear
instructions.
This is actually a separate thread, but dont
worry if thats unclear for now. We can think of
this as a second part of our program than handles
special graphics-related tasks (such as drawing
the window, etc.)
78
Graphics Thread
Both of these threads are your program. You
coded one of the lines of control. Java provides
the other one. That way, things appear to happen
simultaneously--your code executes and the window
gets redrawn, refreshed, etc.
Java quickly switches between your code and the
graphics drawing code, so that both threads
appear to execute at the same time.
79
Who Cares?
This model is very important to understand
because as it turns out, when an event
occurs--such as mouse click, it happens in the
graphics side of the model.
Mouse Click occurs
The code trapping this event appears in the
graphics thread
80
Call backs
Since the event arrived in the graphics half of
our program, we need a way to have it call a
method in our program. This is known as a call
back.
The code trapping this event appears in the
graphics thread
Our event handling code
callback
81
How?
So Java needs to call some event handling code
that we write. The trouble is, how will Java
know what we called our method? We can name them
anything we want, and Java wont necessarily know
what methods handle events.
82
Event Interfaces
Java uses interfaces as its primary event
handling scheme. If you implement an
event-related interface, Java will know which
methods to call. This is because the contract
nature of interfaces requires all methods to
appear in the implementing class.
public void actionPerformed
(ActionEvent e) // code doing something
83
Why Registration?
We are told that event registration must occur
before event handling will occur. What does this
mean? Well, since we can have any class handle
events, we need to tell Java which object
implements the proper event handling
interface. This registers the component as
being interested in receiving callbacks.
Where to callback?
84
Questions?
85
Types of Events
Anything can be an event. Including general
protection faults. But for the most part, good
programming dictates that handled events should
come from the following area of input
86
Java Event Handling Strategies
With this basic understanding, we can
investigate a couple of the primary means of
event handling in Java
1
Event Listeners
Event Adapters
2
87
Listeners
Strategy No. 1
From the discussion about callbacks, we
noted that interfaces were the primary mechanism
for structuring our event handling. There are
numerous event interfaces we can implement,
roughly divided around categories of events. The
next slide lists many of them. Dont freak out
because there are so many. Well highlight the
most commonly used ones. . .
88
Yikes. So Many Choices
Package java.awt.event features
ActionListener MouseListener MouseMotionListener
AdjustmentListener ComponentListener FocusListene
r ContainerListener ItemListener KeyListener Windo
wListener TextListener
As it turns out, the ActionListener is part of
the semantic event group, even though its an
interface. So lets focus on simple events like
MouseListener...
89
Event Listener Summary
We need a class that implements the appropriate
listener type. We need to register a component
as interested in receiving events
addXYZListener ( ltlistener instancegt )
Whatever listener were working with.
E.g. addMouseListener(this) addMouseMotionListe
ner(myEventHandler)
90
Observations
The WindowListener interface required numerous
methods. But only one was important to us. All
the rest were coded as no-op or no operation
methods.
1
2
3
Theres another strategy using adapters, using
inheritance that could have saved us some
trouble...
91
Adapters
Java has built-in classes called event
adapters that implement each of the various
event listeners. But all of these methods are
no-ops.
public class MouseAdapter implements
MouseListener public void
mouseClicked(MouseEvent e) public void
mouseEntered(MouseEvent e) public void
mouseExited(MouseEvent e) public void
mousePressed(MouseEvent e) public void
mouseReleased(MouseEvent e)
WHY?
92
Key to Adapters Inheritance
MouseAdapter
MouseFrame
Why a bunch of no-op methods? Well, if you
subclass the adapter, your class IS-A type of
event listener. And you then only have to
override the one or two methods you care about.
The rest can be inherited as no-ops
93
Big Picture Time
So far, weve tinkered with different ways of
coding very low-level event handling. But what
if our event handling needs are very
general. Consider this simple dialog box
Theres not much interaction that needs to be
supported. Mouse entry/exit might not be needed
at all.
Are you sure you wish to proceed ?
cancel
ok
94
Semantic Events
Wouldnt it be convenient to abstract all of
these small events into one just-tell-me-when-its
-clicked event?
public void mouseClicked(MouseEvent e) public
void mouseEntered(MouseEvent e) public void
mouseExited(MouseEvent e) public void
mousePressed(MouseEvent e) public void
mouseReleased(MouseEvent e)
M1A1 Abstractor
public void actionPerformed(ActionEvent e)
95
Semantic Events
Strategy No. 3
Semantic events provide a means of
handling events at the component level. That is,
you will not address fine-grained events like
mouse entry and exit. Instead, youll only
receive a callback when the component has
received some type of input event
96
Semantic Events
Semantic Event
Components and Firing Event
ActionEvent
Button (activated)
List (double-clicked)
There are numerous event handlers for low-level
events associated with these widgets.
MenuItem (selected)
TextField (typed)
AdjustmentEvent
Scrollbar (moved)
ItemEvent
Checkbox (toggled) CheckboxMenuItem
(selected) Choice (selected) List (selected)
TextEvent
TextComponent (text changes)
Note ALL input is sent into one of these FOUR
categories.
97
Event Handling Options How to Decide
Costs Benefits
Event Listeners (interfaces) Event
Adapters (inheritance) Semantic Events
Must code all methods wasteful no-ops result
Keep all events in single class
Uses up single inheritance opportunity
Good abstraction override those methods you need
Simplifies event handling
Loss of granular control linear code
98
Debugging re Event Handlers
  • Debugging an event-driven program (whether
    applet or graphical application) is more
    tricky than debugging a non-event-driven
    program.
  • With an event-driven Java program, you don't
    explicitly code any kind of event-handling loop
    that "polls" for occurring events, then calls
    the appropriate handler(s) for those events.
  • Instead, the Java internals handle this polling
    action for you. Debugging becomes trickier
    because now you have to make sure that your
    event handling code works correctly.
  • You also have to make sure you're handling the
    correct events in the first place! For
    example, your code for mouseEntered( ) may work
    perfectly, but if you're expecting it to get
    called when the user clicks a mouse button, it
    won't be!

99
Debugging re Event Handlers
  • So, in debugging event-driven programs written
  • with Java, the steps are
  • Be sure you're handling the appropriate events
  • Map out on paper what events get thrown from
    what components, and what class(es) handle
    them.
  • Handle the events appropriately This is the
    kind of debugging you're already familiar with
    Once you're sure the appropriate events are
    getting handled, the rest is being sure the
    event-handling code (and the code that the
    event handlers call) work.

System.out.println is still your friend...
100
Questions?
101
OK, so back to Smiley
  • (demo Graphic3)

102
So its really easy?
  • Well, no. What we will do here is provide you
    with the basic shell from which you can
    experiment by personal study.
  • Dont despair an graphics environment can be a
    lifelong study it took me 6 months before I got
    my first Windows C graphics program working
    well.

103
Basic Graphic Principles
  • The problem with any Graphical User Interface
    (GUI) is that it wants to take control of the
    whole operation away from you and the text user
    interface.
  • At the text interface, all it wants of you is to
    create an object that is an instance of the GUI
    application.
  • Every behavior after that will be under the
    control of the GUI.

These principles apply to all GUIs, not just to
Java.
104
GUI Logical Flow
  • Create an Application object
  • Requests the picture be displayed
  • Request passed to each panels paint method

105
GUI Event Processors
  • Once the constructors have painted the display
    for the first time, the system waits for an
    event.
  • Mouse click
  • Keyboard character
  • Timer tick
  • We must write the code to implement the expected
    behavior
  • As a minimum, we must implement the window close
    mouse click and use it to destroy the application
    instance

Dont panic we dont expect you to know all
this its just here to explain the code we will
provide
106
Start with the Working Class
  • /
  • A class providing the graphics panel for a
    basic face
  • /
  • ltheader stuffgt
  • public class Face1 extends JPanel
  • Dimension screenSize
  • /
  • basic constructor
  • /
  • public Face1( Dimension d )
  • screenSize d
  • /
  • repaint the display
  • /
  • public void paintComponent(Graphics g)
  • ltpainting logicgt

I wonder why I might need the screen size
107
Working Class head stuff
  • /
  • A class providing the storage for a basic face
  • _at_author David M. Smith
  • /
  • import java.util.
  • import java.awt.
  • import java.awt.event.
  • import java.awt.image.
  • import javax.swing.
  • import java.io.
  • public class Face1 extends JPanel

108
Working Class Painting Logic
  • final Color backColor new Color( 200, 200,
    255 )
  • public void paintComponent(Graphics g)
  • Dimension d
  • g.setColor(backColor)
  • d getSize()
  • g.fillRect(0, 0, d.width, d.height) //
    background
  • g.setColor(Color.yellow) // face color
  • g.fillOval(350, 200, 300, 300) // face
    shape
  • g.setColor(Color.black) // outline color
  • g.drawOval(350, 200, 300, 300) // outline
  • g.drawArc(400, 250, 200, 200, 225, 90) //
    smile
  • g.drawArc(400, 250, 200, 199, 225, 90) //
    smile
  • g.drawArc(400, 250, 200, 198, 225, 90) //
    smile
  • g.fillOval(425, 300, 50, 50) // left eye
  • g.fillOval(525, 300, 50, 50) // right eye
  • g.fillRect(490, 350, 20, 50) // nose

109
Simplest of all GUI Application Classes
  • ltheader stuffgt
  • public class Graphic1 extends JFrame
  • Face1 myFace
  • /
  • Constructor
  • /
  • public Graphic1 ()
  • ltconstruction codegt
  • public static void main(String s)
  • Graphic1 g new Graphic1()
  • // Graphic1

110
Details of Constructor Code
  • public Graphic1 ()
  • setTitle("Smiley")
  • ltcreate Window event processorgt
  • setSize (1000,700) // size of frame
  • setLocation (10,10) // location
  • Container cp getContentPane() // frame
    container
  • cp.setLayout(new BorderLayout())
  • myFace new Face1( new Dimension(700, 500)
    )
  • // face size
  • cp.add( myFace, BorderLayout.CENTER )
  • show()

111
Event Processing
  • Lets face it this is the hard part. This is
    one of many ways to solve the problem. It will
    do fine for now.
  • To process Window events, we will use the Adapter
    approach
  • Create an instance of a WindowAdapter()
    implementing a method for each event to which we
    want to respond
  • See the documentation for the class for all the
    choices
  • Register the adapter using the addWindowListener(
    ) method of the parent JFrame class.
  • We could to this separately in neat steps, but
    the code looks ugly anyway, so just do it all in
    one ugly chunk.

112
Adding Event Processing
Add the adapter to the application frame
  • addWindowListener( new WindowAdapter ()
  • public void windowClosing(WindowEvent e)
  • ( (JFrame) e.getSource() ).dispose()
  • )

113
Look at the CodeFace1.javaGraphic1.java
114
Adding Buttons
  • Buttons are very easy interaction devices to
    implement
  • We need to do the following
  • Change the Face class to respond to different
    face expressions requests
  • Put the necessary buttons on a panel
  • Put the panel into the container
  • Handle the mouse events on the buttons using a
    listener

115
Add a frown to the Working Class
  • ltheader stuffgt
  • public class Face2 extends JPanel
  • private Dimension screenSize
  • private boolean smile
  • /
  • basic constructor
  • /
  • public Face2( Dimension d )
  • smile true
  • screenSize d
  • /
  • access the smile data
  • /
  • public void setSmile(boolean v)
  • smile v
  • repaint()

116
Modify the Painting Logic
  • public void paintComponent(Graphics g)
  • Dimension d
  • g.setColor(backColor)
  • d getSize()
  • g.fillRect(0, 0, d.width, d.height) //
    background
  • g.setColor(Color.yellow) // face color
  • g.fillOval(350, 200, 300, 300) // face
    shape
  • g.setColor(Color.black) // outline color
  • g.drawOval(350, 200, 300, 300) // outline
  • if( smile )
  • g.drawArc(400, 250, 200, 200, 225, 90) //
    smile
  • g.drawArc(400, 250, 200, 199, 225, 90) //
    smile
  • g.drawArc(400, 250, 200, 198, 225, 90) //
    smile
  • else // frown
  • g.drawArc(400, 425, 200, 200, 45, 90) //
    frown
  • g.drawArc(400, 424, 200, 199, 45, 90) //
    frown
  • g.drawArc(400, 423, 200, 198, 45, 90) //
    frown

117
Add Buttons to the GUI Application Class
  • ltheader stuffgt
  • public class Graphic2 extends JFrame
  • Face2 myFace
  • /
  • Constructor
  • /
  • public Graphic2 ()
  • ltadd to the construction codegt
  • class EventHandler implements MouseListener
  • ltadd event handler for the buttonsgt
  • public static void main(String s)
  • Graphic2 g new Graphic2()

118
Constructor Code
  • public Graphic2 ()
  • setTitle("Smiley")
  • EventHandler eh
  • ltcreate Window event processorgt
  • setSize (1000,700) // size of frame
  • setLocation (10,10) // location
  • ltcreate buttonsgt
  • Container cp getContentPane() // frame
    container
  • cp.setLayout(new BorderLayout())
  • myFace new Face2( new Dimension(700, 500)
    )
  • // face size
  • cp.add( myFace, BorderLayout.CENTER )
  • show()

119
Create Buttons
  • JPanel panel new JPanel()
  • panel.setLayout(new FlowLayout())
  • JButton smileB new JButton( "Smile" )
  • eh new EventHandler (this, smileB)
  • smileB.addMouseListener(eh)
  • panel.add(smileB)
  • JButton frownB new JButton( "Frown" )
  • eh new EventHandler (this, frownB)
  • frownB.addMouseListener(eh)
  • panel.add(frownB)
  • Container cp getContentPane()
  • cp.setLayout(new BorderLayout())
  • cp.add( panel, BorderLayout.SOUTH )

Smile button
Frown button
Install buttons
120
We will use an Event Handler for the Mouse
  • class EventHandler implements MouseListener
  • Graphic2 theFrame
  • JButton button
  • public EventHandler (Graphic2 theFrame,
    JButton button)
  • this.theFrame theFrame
  • this.button button
  • public void mouseClicked(MouseEvent e)
  • ltcode for the mouse clickgt
  • public void mousePressed(MouseEvent e)
  • public void mouseEntered(MouseEvent e)
  • public void mouseExited(MouseEvent e)
  • public void mouseReleased(MouseEvent e)

121
Mouse Click Code
  • class EventHandler implements MouseListener
  • Graphic2 theFrame
  • JButton button
  • public EventHandler (Graphic2 theFrame,
    JButton button)
  • this.theFrame theFrame
  • this.button button
  • public void mouseClicked(MouseEvent e)
  • String com button.getText()
  • if (com.equals("Smile"))
  • myFace.setSmile(true)
  • else if (com.equals("Frown"))
  • myFace.setSmile(false)

Put this class inside the Graphic2 class to
achieve access to the Face reference
122
Look at the CodeFace2.javaGraphic2.java
123
Adding Timer Operations
  • The last and of course, ugliest challenge is
    adding autonomous timer capability.
  • Winking an eye is the simplest possible
    application
  • Our implementation tools will be sufficient for
    anything you need to do for the foreseeable
    future
  • The biggest issue is that the basic Face needs to
    inherit real-time capabilities from the Runnable
    class.
  • Your choices
  • Accept that this works and live with it
  • Embark on a 3 year PhD study to trade off
    different approaches
  • recommended

124
Add winking to the Working Class
  • public class Face3 extends JPanel implements
    Runnable
  • private Dimension screenSize
  • private boolean smile
  • private boolean wink
  • public boolean isRunning true
  • // constructor
  • public Face3( Dimension d )
  • screenSize d
  • smile true
  • wink false
  • // stop the winking
  • public void stop()
  • isRunning false
  • // run the winking

125
Modify the Painting Logic
  • public void paintComponent(Graphics g)
  • ltsame setup as beforegt
  • if( smile )
  • g.drawArc(400, 250, 200, 200, 225, 90) //
    smile
  • g.drawArc(400, 250, 200, 199, 225, 90) //
    smile
  • g.drawArc(400, 250, 200, 198, 225, 90) //
    smile
  • else
  • g.drawArc(400, 425, 200, 200, 45, 90) //
    frown
  • g.drawArc(400, 424, 200, 199, 45, 90) //
    frown
  • g.drawArc(400, 423, 200, 198, 45, 90) //
    frown
  • if( wink )
  • g.drawArc(425, 300, 50, 50, 180, 180) //
    closed eye
  • g.drawArc(425, 300, 50, 49, 180, 180) //
    closed eye
  • g.drawArc(425, 300, 50, 48, 180, 180) //
    closed eye
  • else
  • g.fillOval(425, 300, 50, 50) // left
    eye
  • g.fillOval(525, 300, 50, 50) // right eye

126
Add Buttons to the GUI Application Class
  • ltheader stuffgt
  • public class Graphic3 extends JFrame
  • Face3 myFace
  • private Thread faceThread
  • /
  • Constructor
  • /
  • public Graphic3 ()
  • ltadd to the construction codegt
  • class EventHandler implements MouseListener
  • ltadd events for the new buttonsgt
  • public static void main(String s)
  • Graphic3 g new Graphic3()

127
Constructor Code
  • public Graphic3 ()
  • setTitle("Smiley")
  • EventHandler eh
  • ltminor change to event processorgt
  • setSize (1000,700) // size of frame
  • setLocation (10,10) // location
  • ltcreate two more buttonsgt
  • Container cp getContentPane() // frame
    container
  • cp.setLayout(new BorderLayout())
  • myFace new Face3( new Dimension(700, 500)
    )
  • // face size
  • cp.add( myFace, BorderLayout.CENTER )
  • ltinsert button panelgt
  • show()

128
Minor Change to Window Event Processing
  • addWindowListener( new WindowAdapter ()
  • public void windowClosing(WindowEvent e)
  • myFace.isRunning
    false
  • ( (JFrame) e.getSource() ).dispose()
  • )

This stops the face wink process when you close
the window.
129
Create two more Buttons
  • JButton frownB new JButton( "Frown" )
  • eh new EventHandler (this, frownB)
  • frownB.addMouseListener(eh)
  • panel.add(frownB)
  • JButton winkB new JButton( "Wink" )
  • eh new EventHandler (this, winkB)
  • winkB.addMouseListener(eh)
  • panel.add(winkB)
  • JButton stopB new JButton( "Stop" )
  • eh new EventHandler (this, stopB)
  • stopB.addMouseListener(eh)
  • panel.add(stopB)

Frown button
Wink button
Stop button
lt Install buttons as before gt
130
Mouse Click Code
  • class EventHandler implements MouseListener
  • public void mouseClicked(MouseEvent e)
  • String com button.getText()
  • if (com.equals("Smile"))
  • myFace.setSmile(true)
  • else if (com.equals("Frown"))
  • myFace.setSmile(false)
  • else if (com.equals("Wink"))
  • faceThread new Thread(myFace)
  • myFace.isRunning true
  • faceThread.start()
  • else if (com.equals("Stop"))
  • myFace.isRunning false

131
Final Look at the CodeFace3.javaGraphic3.java
132
Questions?
133
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com