2 event driven programming
DESCRIPTION
this is a Java swing tutorialTRANSCRIPT
-
5/24/2018 2 Event Driven Programming
1/28
Event-Driven Programming
-
5/24/2018 2 Event Driven Programming
2/28
Procedural vs. Event-DrivenProgramming
Procedural programming is executed in procedural order
procedural - of or relating to procedure
procedure - a series of steps followed in a regular definite
order
In event-driven programming, code is executed uponactivation of events
e.g. menu buttons can be selected in any order
2
-
5/24/2018 2 Event Driven Programming
3/28
Taste of Event-DrivenProgramming
The example displays three buttons in the frame.
The content pane's background colour changes when abutton is clicked.
3
ButtonTest
-
5/24/2018 2 Event Driven Programming
4/28
Events
An event can be defined as a type of signal to theprogram that something has happened
The event is generated by external user actions such as
mouse movements, mouse clicks, and keystrokes, or bythe operating system, such as a timer
4
ColorActionActionListener
JButton
actionPerformed
-
5/24/2018 2 Event Driven Programming
5/28
The Delegation Model
5
source: SourceClass
+addXListener(listener:XListener)
listener: ListenerClass
User
Action
Trigger an event
XListener
+handler(event: XEvent)
Register by invoking
source.addXListener(listener);(a) A generic source component
with a generic listener
source: JButton
+addActionListener(listener: ActionListener)
listener: CustomListenerClass
ActionListener
+actionPerformed(event: ActionEvent)
Register by invoking
source.addActionListener(listener);(b) A JButton source component
with an ActionListener
-
5/24/2018 2 Event Driven Programming
6/28
Internal Function of a SourceComponent
6
source: SourceClass
+addXListener(XListener listener)
(a) Internal function of a generic source object
event:XEvent listener1listener2listenern
Keep it a list
Invokelistener1.handler(event)
listener2.handler(event)
listenern.handler(event)
An event istriggered
source: JButton
+addActionListener(ActionListener listener)
(b) Internal function of a JButton object
event:
ctionEvent
listener1listener2listenern
Keep it a list
Invokelistener1.actionPerformed(event)
listener2.actionPerformed(event)
listenern.actionPerformed(event)
An event istriggered
-
5/24/2018 2 Event Driven Programming
7/28
The Delegation Model: Example
7
JButton okButton = new JButton("OK");
ActionListener listener = new OKListener();
okButton.addActionListener(listener);
-
5/24/2018 2 Event Driven Programming
8/28
Event Classes
8
AWTEventEventObject
AdjustmentEvent
ComponentEvent
TextEvent
ItemEvent
ActionEvent
InputEvent
WindowEvent
Mouse
KeyEv
ContainerEvent
FocusEvent
PaintEvent
ListSelectionEvent
-
5/24/2018 2 Event Driven Programming
9/28
Event Information
An event object contains whatever properties whichpertain to the event
You can identify the source object of the event using
the getSource() instance method in the EventObjectclass
The subclasses of EventObject deal with special types ofevents, such as button actions, window events,
component events, mouse movements, and keystrokes
9
-
5/24/2018 2 Event Driven Programming
10/28
Selected User ActionsUser Action Source Event Generated
Click a button JButton ActionEvent
Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEventPress return on a text field JTextField ActionEvent
Window opened, closed, etc Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent
10
-
5/24/2018 2 Event Driven Programming
11/28
Selected Event HandlersEvent Class Listener Interface Handlers
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
WindowEvent WindowListener windowClosing(WindowEvent)windowOpened(WindowEvent)
windowIconified(WindowEvent)windowDeiconified(WindowEvent)windowClosed(WindowEvent)windowActivated(WindowEvent)windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)componentRemoved(ContainerEvent)
MouseEvent MouseListener mousePressed(MouseEvent)mouseReleased(MouseEvent)mouseClicked(MouseEvent)mouseEntered(MouseEvent)mouseExited(MouseEvent)
KeyEvent KeyListener keyPressed(KeyEvent)keyReleased(KeyEvent)keyTypeed(KeyEvent)
11
-
5/24/2018 2 Event Driven Programming
12/28
Inner Class Listeners
A listener class is designed specifically to create alistener object for a GUI component (e.g., a button)
It will not be shared by other applications.
So, it is appropriate to define the listener class inside theframe class as an inner class
12
-
5/24/2018 2 Event Driven Programming
13/28
Inner Classes
Inner class: A class is a member of another class.
Advantages: In some applications, you can use an innerclass to make programs simple.
An inner class can reference the data and methodsdefined in the outer class in which it nests, so you donot need to pass the reference of the outer class to theconstructor of the inner class.
13
-
5/24/2018 2 Event Driven Programming
14/28
Inner Classes (cont.)
Inner classes can make programs simple and concise.
An inner class supports the work of its containing outerclass and is compiled into a class named
OuterClassName$InnerClassName.class. For example,the inner class InnerClass in OuterClass is compiled intoOuterClass$InnerClass.class.
14
-
5/24/2018 2 Event Driven Programming
15/28
Inner Classes (cont.)
An inner class can be declared public, protected, orprivate subject to the same visibility rules applied to amember of the class
An inner class can be declared static A static inner class can be accessed using the outer class
name
A static inner class cannot access nonstatic members of theouter class
15
-
5/24/2018 2 Event Driven Programming
16/28
Anonymous Inner Classes Anonymous class is declared and initialized simultaneously.
As anonymous class has no name, it can be used only once.
An anonymous inner class must always extend a superclass orimplement an interface, but it cannot have an explicitextends or implements clause.
An anonymous inner class must implement all the abstractmethods in the superclassor in the interface.
An anonymous inner class always uses the no-arg constructorfrom its superclass to create an instance. If an anonymousinner class implements an interface, the constructor isObject().
An anonymous inner class is compiled into a class namedOuterClassName$n.class. For example, if the outer class Testhas two anonymous inner classes, these two classes arecompiled into Test$1.class and Test$2.class.
16
-
5/24/2018 2 Event Driven Programming
17/28
Anonymous Inner Classes cont.. You use them in situations where you need to create a class
for a specific purpose inside another function, e.g., as a
listener, as a runnable (to spawn a thread), etc.
The idea is that you call them from inside the code of afunction so you never refer to them elsewhere, so youdon't need to name them. The compiler just enumeratesthem.
They are essentially syntactic sugar, and should generally bemoved elsewhere as they grow bigger
We can just instantiate an anonymous inner class without
actually making a separate class.
Use this technique for "quick and dirty" tasks where making anentire class feels unnecessary. Having multiple anonymousinner classes that do exactly the same thing should berefactored to an actual class, be it an inner class or aseparate class.
-
5/24/2018 2 Event Driven Programming
18/28
Demo Using Anonymous Inner Classes18
PlafTest
-
5/24/2018 2 Event Driven Programming
19/28
Example: Handling Window Events
Any subclass of the Window class can generate the followingwindow events: window opened, closing, closed, activated,deactivated, iconified, and deiconified.
This program creates a frame, listens to the window events, anddisplays a message to indicate the occurring event.
19
TestWindowEvent
-
5/24/2018 2 Event Driven Programming
20/28
Using Adapters
To reduce the number of unimplemented listener interfacemethods, you can make use of an adapter instead
The easiest way to use an adapter is to use an anonymousinner class
import java.awt.event.WindowAdapter;...addWindowListener(new WindowAdapter() {public void windowClosing() {System.exit(0);});
The WindowAdapter class implements all of the
WindowListener methods
20
-
5/24/2018 2 Event Driven Programming
21/28
MouseEvent
21
java.awt.event.MouseEvent
+getButton(): int
+getClickCount(): int+getPoint(): java.awt.Point
+getX(): int
+getY(): int
Indicates which mouse button has been clicked.
Returns the number of mouse clicks associated with this event.Returns a Point object containing the x and y coordinates.
Returns the x-coordinate of the mouse point.
Returns the y-coordinate of the mouse point.
java.awt.event.InputEvent
+getWhen(): long
+isAltDown(): boolean
+isControlDown(): boolean
+isMetaDown(): boolean
+isShiftDown(): boolean
Returns the timestamp when this event occurred.
Returns whether or not the Alt modifier is down on this event.
Returns whether or not the Control modifier is down on this event.
Returns whether or not the Meta modifier is down on this event
Returns whether or not the Shift modifier is down on this event.
-
5/24/2018 2 Event Driven Programming
22/28
Handling Mouse Events
Java provides two listener interfaces, MouseListener andMouseMotionListener, to handle mouse events.
The MouseListenerlistens for actions such as when the mouse ispressed, released, entered, exited, or clicked.
The MouseMotionListenerlistens for actions such as dragging ormoving the mouse.
22
-
5/24/2018 2 Event Driven Programming
23/28
Handling Mouse Events
23
java.awt.event.MouseListener
+mousePressed(e: MouseEvent): void
+mouseReleased(e: MouseEvent): void
+mouseClicked(e: MouseEvent): void
+mouseEntered(e: MouseEvent): void
+mouseExited(e: MouseEvent): void
Invoked when the mouse button has been pressed on the
source component.
Invoked when the mouse button has been released on the
source component.Invoked when the mouse button has been clicked (pressed and
released) on the source component.
Invoked when the mouse enters the source component.
Invoked when the mouse exits the source component.
java.awt.event.MouseMotionListener
+mouseDragged(e: MouseEvent): void
+mouseMoved(e: MouseEvent): void
Invoked when a mouse button is moved with a button pressed.
Invoked when a mouse button is moved without a button
pressed.
-
5/24/2018 2 Event Driven Programming
24/28
Example: Moving Message UsingMouse
24
MoveMessageDemo
-
5/24/2018 2 Event Driven Programming
25/28
Example: Handling Complex MouseEvents
25
ScribbleDemo
-
5/24/2018 2 Event Driven Programming
26/28
Handling Keyboard Events
To process a keyboard event, use the following handlersin the KeyListener interface:
keyPressed(KeyEvent e)
Called when a key is pressed. keyReleased(KeyEvent e)
Called when a key is released.
keyTyped(KeyEvent e)
Called when a key is pressed and then
released.
26
-
5/24/2018 2 Event Driven Programming
27/28
The KeyEvent Class
Methods:
getKeyChar() method
getKeyCode() method
Keys:
Home VK_HOME
End VK_END
Page Up VK_PGUP
Page Down VK_PGDN
etc...
27
-
5/24/2018 2 Event Driven Programming
28/28
Example: Keyboard EventsDemo
28
KeyEventDemo