MouseEvent - Departamento de Ingeniería de Sistemas e Industrial

Download Report

Transcript MouseEvent - Departamento de Ingeniería de Sistemas e Industrial

ertificación en
AVA
Universidad Nacional de Colombia
Facultad de Ingeniería
Departamento de Sistemas
10. EVENTS
 Objectives
 Interface Event
 Event Delegation Model
 The Event Class Hierarchy
 Event Listeners
 Explicit Event Enabling
 Adapters
Objectives
• Write code to implement listener classes and
methods, and in listener methods, extract information
from the event to determine the affected component,
mouse position, nature, and time of the event. State
the event classname for any specified event listener
interface in the java.awt.event package.
Interface Event
When the user clicks a button, types text,
uses the mouse, or performs any other
interface-related action in your applet, an
interface event occurs.
When an event occurs, the applet is notified
and takes the appropriate action.
Interface Event
In GUI, the program responds to user events
when they happen because the user directs
the program flow by manipulating the
controls in the applet.
Java declares ActionListener as an interface
to let you use the ActionListener methods.
You can extend the Applet class to create
your applet, and implement the
ActionListener interface to use the ActionListener methods as well.
Interface Event
Most of the event classes reside in the
java.awt.event package.
The class that implements the ActionListener
interface does not have to be the applet's
main class. In fact, you can create an entirely
new class, which helps break up the code.
Event Delegation Model
Delegation-Based Event Model
Listener ---------------- Component
event delegation model
a component may be told which object or
objects should be notified when the
component generates a particular kind of
event
If a component is not interested in an event
type, then events of that type will not be
propagated
The delegation model is based on four
concepts:
•
•
•
•
Event classes
Event listeners
Explicit event enabling
Adapters
Event Delegation Model
The delegation-based event model passes
events from source controls to Listener
objects.
That means you will connect a Listener to
your component.
When an event occurs, the Listener object
will hear it.
Event Delegation Model
In this case, you will make the Listener
object the applet object itself by connecting
your applet to your component as a listener,
using the button's addActionListener()
method.
To indicate that you want the applet itself to
be the component's listener, you would need
to be able to pass the applet as an argument
to addActionListener().
public class clicker extends Applet implements ActionListener
Event Delegation Model
That is accomplished with the this keyword,
which refers to the current object.
Then, when there are component events,
they will be sent to your applet.
The Event Class Hierarchy
Most of the event classes reside in the
java.awt.event package
The Event Class Hierarchy
java.util.eventobject
java.awt.AWTEvent
ActionEvent
TextEvent
AdjustmentEvent
ComponentEvent
ItemEvent
WindowEvent
ContainerEvent
FocusEvent
KeyEvent
InputEvent
PaintEvent
MouseEvent
java.util.EventObject: topmost superclass of all
the new event classes is. It is a very general
class, with only one method of interest:
• Object getSource(): returns the object that
originated the event
One subclass of EventObject is
java.awt.AWTEvent, which is the superclass
of all the delegation model event classes.
Again, there is only one method of interest:
• int getlD(): returns the ID of the event
An event's ID is an int that specifies the
exact nature of the event. For example, an
instance of the MouseEvent class can
represent one of seven occurrences: a click,
a drag, an entrance, an exit, a move, a
press, or a release
Each of these possibilities is represented by
an int:
MouseEvent.MOUSE_CLICKED,
MouseEvent.MOUSE_DRAGGED, and so on.
Subclasses of java.awt.AWTEvent
event types that can be generated by the
various AWT components
• ActionEvent:
generated by activation of components
• AdjustmentEvent:
generated by adjustment of adjustable
component such as scroll bars
• ContainerEvent:
generated when components are added to or
removed from a container
• FocusEvent:
generated when a component receives or
loses input focus
• ItemEvent:
generated when an item is selected from a
list, choice, or check box
• KeyEvent:
generated by keyboard activity
• MouseEvent:
generated by mouse activity
• PaintEvent:
generated when a component is painted
• TextEvent:
generated when a text component is modified
• WindowEvent:
generated by window activity (such as
iconifying or de-iconifying)
The InputEvent superclass has a getWhen()
method that returns the time when the
event took place; the return type is long
The MouseEvent class has getX() and getY()
methods that return the position of the
mouse within the originating component at
the time the event took place; the return
types are both int
Event Listeners
An event listener is an object to which a
component has delegated the task of
handling a particular kind of event
• When the component experiences input, an
event of the appropriate type is
constructed;
• the event is then passed as the parameter
to a method call on the listener
• A listener must implement the interface
that contains the event-handling method
Example: a button in an applet
When the button is clicked, an action event
is to be sent to an instance of class
MyActionListener
1. class MyActionListener implements ActionListener {
2.
public void actionPerformed( ActionEvent ae ) {
3.
System.out.println( "Action performed." );
4.
}
5. }
1. public class ListenerTest extends Applet {
2.
public void init() {
3.
Button btn = new Button( "OK" );
3.
MyActionListener listener = new
4.
MyActionListener();
5.
btn.addActionListener( listener );
6.
add( btn );
7.
}
8. }
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class click extends Applet implements
ActionListener
{
TextField texto;
Button boton;
public void init()
{
texto = new TextField(20);
add(texto);
texto.setText("Bienvenido a Java");
boton = new Button("Haga Click!");
add(boton);
boton.addActionListener(this);
}
}
public void actionPerformed(ActionEvent event)
{
String msg = new String("Welcome to Java");
if(event.getSource() == boton)
{
texto.setText(msg);
}
}
A standard formula for giving an action
listener to a component
1. Create a listener class that implements the
ActionListener interface
2. Construct the component
3. Construct an instance of the listener class
4. Call addActionListener() on the component,
passing in the listener object
A component may have multiple listeners for
any event type
There is no guarantee that listeners will be
notified in the order in which they were
added
There is also no guarantee that all listener
notification will occur in the same thread;
thus listeners must take precautions
against corrupting shared data
Listener Interfaces
Interface
Interface methods
Add Method
ActionListener
actionPerformed( ActionEvent )
addActionListener()
AdjustmentListener
adjustmentValueChanged(
AdjustmentEvent )
addAdjustmentListener()
ComponentListener
componentHidden( ComponentEvent )
componentMoved( ComponentEvent )
componentResized( ComponentEvent )
componentShown( ComponentEvent )
addComponentlistener()
ContainerListener
componentAdded( ContainerEvent )
componentRemoved( ContainerEvent )
addContainerListener()
FocusListener
focusGained( FocusEvent )
focusLost( FocusEvent )
addFocusListener()
Listener Interfaces ...
Interface
Interface methods
Add Method
ItemListener
itemStateChanged( ItemEvent )
addItemListener()
KeyListener
keyPressed( KeyEvent )
keyReleased( KeyEvent )
keyTyped( KeyEvent )
addKeyListener()
MouseListener
mousedClicked( MouseEvent )
mouseEntered( MouseEvent )
mouseExited( MouseEvent )
mousePressed( MouseEvent )
mouseReleased( MouseEvent )
addMouseListener()
MouseMotionListener
mouseDragged( MouseEvent )
mouseMoved( MouseEvent )
addMouseMotionListener()
Listener Interfaces ...
Interface
Interface methods
Add Method
TextListener
textValueChanged( TextEvent )
addTextListener()
WindowListener
windowActivated( WindowEvent )
windowClosed( WindowEvent )
windowClosing( WindowEvent )
windowDeactivated( WindowEvent )
windowDeiconified( WindowEvent )
windowlconified( WindowEvent )
windowOpened( WindowEvent )
addWindowListener()
An event listener may be removed from a
component's list of listeners by calling a
removeXXXListener() method,
passing in the listener to be removed
btn.removeActionListener( al );
Explicit Event Enabling
There is an alternative to delegating a
component's events
It is possible to subclass the component and
override the method that receives events
and dispatches them to listeners
Example:
components that originate action events have
a method called processActionEvent(
ActionEvent ), which dispatches its action
event to each action listener
1. class MyBtn extends Button {
2.
public MyBtn( String label ) {
3.
super( label );
4.
enableEvents( AWTEvent.ACTION_EVENT_MASK );
5.
}
6.
7.
public void processActionEvent( ActionEvent ae ) {
8.
System.out.println( "Processing an action event." );
9.
super.processActionEvent( ae );
10.
}
11. }
you can always make a component subclass
handle its own events by making the subclass
an event listener of itself
1. class MyBtn extends Button implements
ActionListener {
2.
public MyBtn( String label ) {
3.
super( label );
4.
addActionListener( this );
5.
}
6.
7.
public void actionPerformed( ActionEvent ae ) {
8.
// Handle the event here
9.
}
10.}
The only difference between this strategy and the
enableEvents() strategy is the order in which
event handlers are invoked
When you explicitly call enableEvents(), the
component's processActionEvent() method will
be called before any action listeners are notified
When the component subclass is its own event
listener, there is no guarantee as to order of
notification
Event Masks
Each of the 11 listener types has a corresponding
XXX_EVENT_MASK
constant defined in the AWTEvent class, and
corresponding
processXXXEvent()
methods
Event Masks
Mask
AWTEvent.ACTION EVENT MASK
Method
processActionEvent()
AWTEvent.ADJUSTMENT EVENT MASK
processAdjustmentEvent()
AWTEvent.COMPONENT EVENT MASK
processComponentEvent()
AWTEvent.CONTAINER EVENT MASK
processContainerEvent()
AWTEvent.FOCUS EVENT MASK
process FocusEvent()
AWTEvent.ITEM EVENT MASK
processItemEvent()
AWTEvent.KEY_EVENT_MASK
processKeyEvent()
AWTEvent.MOUSE_EVENT_MASK
processMouseEvent()
AWTEvent.MOUSE_MOTION_EVENT_MASK
processMouseMotionEvent()
AWTEvent.TEXT_EVENT_MASK AWT
processTextEvent()
Event.WINDOW EVENT MASK
processWindowEvent()
The strategy of explicitly enabling events for a
component:
1. Create a subclass of the component
2. In the subclass constructor, call
enableEvents( AWTEvent.XXXEVENT_MASK
)
3. Provide the subclass with a
processXXXEvent() method; this method
should call the superclass' version before
returning
Adapters
Example:
Catching iconified events on a frame
1. class MyIkeListener
implements WindowListener {
2.
public void windowIconified( WindowEvent we ) {
3.
// process the event
4.
}
5. }
The java.awt.event provides seven adapter classes,
one for each listener interface that defines more
than just a single method
An adapter is simply a class that
implements an interface by providing
do-nothing methods
1. class MylkeListener extends WindowAdapter {
2.
public void windowIconified( WindowEvent we ) {
3.
// process the event
4.
}
5. }
Adapters
Adapter Class
Listener Interface
___________________________________________________________
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
Windowlistener