Chapter 9 AWT Event Model
This module discusses the user input mechanism of the event-driven graphical user interface (GUI).
Section 1 related issues
Discussion - The following is a question related to this module:
- Which parts are necessary for a graphical user interface?
- How does a graphical program handle mouse click or other type of user interaction?
Second section
After completing this module, you should be able to:
- Write code to handle events that occur in the graphical user interface
- Describe the concept of Adapter class, including how to use them
- Determine user action generated by the event based on the details of the event object
- Create a suitable interface and event processor for various types of events.
Section III What is an event?
What is an event?
- Event - Description Object What happened
- Event source - generator generator
- Event Processor - Receive Events, Interpret Events and Handling User Interactions
If the user performs an action (mouse click and button) in the user interface layer, this will result in an event. The event is the object that is described. There are various types of event class to describe various types of user interactions.
9.3.1 Event Source
The event source is a generator of an event. For example, click on the mouse on the Button component to generate an ActionEvent in this button. This ActionEvent instance is an object that contains an object of information about the event that happened. This information includes:
- getActionCommand- Returns the name of the command associated with the action.
- getModifiers - Returns the modifiers held during action.
9.3.2 Event Processor
The event processor is a method of receiving events, interpreting events and handling user interactions.
Section IV JDK1.0 Event Model and JDK1.2 Event Model
Comparison of event models of JDK1.0 and JDK1.2
- Hierarchical model (JDK 1.0)
- Entrusted model (JDK 1.2)
In JDK1.1, the method of event reception and processing has changed. This section will compare the previous event model (JDK1.0) and the current event model (JDK1.1 and JDK1.2).
JDK1.0 uses a hierarchical event model, while JDK1.1 and higher versions use a commissioned event model.
9.4.1 Hierarchy Model (JDK1.0)
The hierarchical model is based on the container. The event is first sent to the component and then spreads upward along the container level. An event that is not processed is automatically transmitted to the container of the component.
Comparison of event models of JDK1.0 and JDK1.2
For example, in the following figure, the mouse button on the Button object (included in the panel on a frame) first sends an action event to Button. If it is not processed by Button, this event will be sent to PANEL, and if it is still not processed there, this event will be sent to FRAME.
Hierarchical model (JDK1.0)
advantage
- Simple, and very suitable for object-oriented programming environments.
Disadvantage
- The event can only be processed by a component that produces this event or a container containing this component.
- To handle events, you must define subclasses of components that receive this event, or create a HandleEvent () method in the baselane.
Hierarchical model (JDK1.0) (continued)
This model has a significant advantage:
- It is simple, and it is very suitable for object-oriented programming environments; However, this model also has a disadvantage:
- The event can only be processed by a component that produces this event or a container containing this component. This restriction violates a basic principle of object-oriented programming: The function should be included in the most suitable class. The class that is most suitable for processing events is often not a member of the vessel hierarchy of the source component.
- A large number of CPU cycles are wasted on the incidents that are not related. Any event that is not related to the program or is not important will spread along the container hierarchy until it is finally abandoned. There is no simple way to filter events.
- To handle events, you must define subclasses of components that receive this event, or create a huge HandleEvent () method in the baselane.
The entrusted event model is introduced in JDK1.1. In this model, the event is sent to a component that generates this event, however, a class, which is said to be called a listener depends on each component, which contains an event processor to receive and process this event. With this method, the event processor can be arranged in an object that is separated from the source component. The listener is a class that implements the Listener interface.
The event is an object that is only reported to the registered listener. Each event has a corresponding listener interface that specifies which methods must be defined in a class that is suitable for receiving the type of event. A class that implements interfaces that define those methods can be registered as a listener.
9.4.2 Entrust model
Events issued from components that have not registered listeners will not be propagated.
For example, this is a simple frame containing only a single Button.
1. IMPORT JAVA.AWT. *;
2.
3.public class testbutton {
4.public static void main (string args []) {
5.frame f = new frame ("test");
6.Button B = New Button ("Press ME!");
7.b.AddActionListener (New ButtonHandler ());
8.f.add (b, "center");
9.f.pack ();
10.f.setvisible (TRUE);
11.}
12.}
The ButtonHandler class is a processor class that will be delegated to this class.
1. IMPORT JAVA.AWT.EVENT. *;
2.
3.public class buttonhandler imports anctionsListener {
4.Public void actionperformed (ActionEvent E) {
5.system.out.println ("Action Occurred");
6.System.Out.println ("Button's Label IS: '
7. E.GetActionCommand ());
8.}
9.}
These two examples are as follows:
- Button class has an AddActionListner method.
- The AddActionListner interface defines a method ActionPerformed that receives an ActionEvent.
- When you create a Button object, this object can be registered as an ACTIONEvents using the AddActionListener method. Calling this method with a parameter of a class that implements an ActionListener interface.
Entrusted model (JDK1.1 or higher)
advantage
- The event will not be processed unexpectedly. - It is possible to create and use the Adapter class to classify event action.
- The entrustment model is conducive to distributing work into each class.
Disadvantage
- It is not easy to transplant the JDK1.0 code to JDK1.1.
Entrusted model (JDK1.1 or higher) (continued)
- An ActionEvent event will be sent with a mouse with a mouse on the Button object. This ActionEvent event is received using the ActionPerFormed () method of all ActionListener registered using the AddActionListener () method.
- getActionCommand () method of the ActionEvent class returns the command name associated with the action. With the click action of the button, the Button label will be returned.
This method has several advantages:
- The event will not be processed unexpectedly. In the hierarchy model, an event may be propagated to the container and is processed at a non-expected hierarchy.
- It is possible to create and use the Adapter class to classify event action.
- The entrustment model is conducive to distributing work into each class.
- The new event model provides support for JavaBeans.
This method also has a disadvantage:
- Although the current JDK supports the entrustment model and JDK1.0 event model, JDK1.0 and JDK1.1 cannot be mixed.
Section 5 behavior of graphical user interface
9.5.1 Event type
We have already introduced the general mechanism of receiving events from components in a single type event context. The hierarchical diagram of the event class is shown below. Many event classes are in the java.awt.event package, there are also some event classes in the API.
For each type of event, there is an interface, this interface must be implemented by an object of the class you want to receive this event. This interface also requires defining one or more methods. These methods are called when a specific event occurs. Table 9-1 lists these (event) types and gives the interface name corresponding to each type, and the required definition method. The names of these methods are easy to remember, and the name indicates the source or condition that can cause this method being called.
Table 9-1 Method Types and Interfaces
Category
Interface name
Methods
Action
ActionListener
ActionPerformed (ActionEvent)
Item
Itemlistener
ItemStateChanged (itemEvent)
Mouse motion
MouseMotionListener
mousedragged (mouseevent)
Mousemoved (MouseEvent)
Mouse Button
Mouselistener
MousePressed (MouseEvent)
mouseeleased (mouseevent)
MouseEntered (MouseEvent)
MouseExited (mouseevent)
mouseclicked (mouseevent)
Key
Keylistener
KeyPressed (keyevent)
Keyreleased (KeyEvent)
Keytyped (KeyEvent)
FOCUS
FocusListener
Focusgained (Focusevent)
FOCUSLOST (FOCUSEVENT)
Adjustment
AdjustmentListener
AdjustmentValueChanged
Adjustmentest
Component
ComponentListener
ComponentMoved (Componentevent)
Componenthidden (ComponENTEVENT)
Componentresized (Componentevent)
ComponentShown (ComponENTEVENT) Table 9-1 Method Types and Interfaces (Continued)
9.5.2 Complex example
This section will investigate a more complex Java software example. It will track the mouse when the mouse is pressed, the mouse movement (mouse drag). This example will also monitor the movement of the mouse (mouse movement) when the mouse is not pressed.
When the mouse is pressed or not pressed, the event generated by the mobile mouse will be enabled by the object of the class of the MouseMotionListener interface. This interface requires two methods, mousedragged () and mousemoved (). Even if you only drag your mouse, you must also provide these two methods. However, the body of mousemoved () can be empty.
To check other mouse events, including the mouse click, you must define the mouselistener interface. This interface includes several events, namely: mouseentered, mouseexited, mousepressed, mousereleased and mouseclicked.
When a mouse or keyboard event occurs, information about the position of the mouse and the pressed key can be obtained from the event. code show as below:
1. IMPORT JAVA.AWT. *;
2. IMPORT JAVA.AWT.EVENT. *;
3.
4.Public Class Twolisten IMPLEMENTS
5.mouseMotionListener, Mouselistener {
6.Private frame f;
7.Private textfield TF;
8.
9.public static void main (string args []) {
10.Twolisten two = new twolisten ();
11.Two.go ();
12.}
13.
Complex example (continued)
1.public void Go () {
2.F = New frame ("Two listener Example");
3.F.Add (New Label ("Click and Drag The Mouse",
4. "BorderLayout.North");
5.TF = New TextField (30);
6.f.add (TF, "BorderLayout.South);
7.
8.f.addmouseMotionListener (this);
9.f.addmouselistener (this);
10.f.setsize (300, 200);
11.f.setvisible (TRUE);
12.}
13.
14.// These area MouseMotionListener Events
15.public void mousedraged (mouseevent e) {
16.String s =
17. "Mouse Dragging: x =" E.GETX ()
18. "y =" E.GETY ();
19.Tf.setText (s);
20.}
twenty one.
22.public void mousemoved (mouseevent e) {
twenty three.}
twenty four.
25.// There Are MouseListener Events
26.public void mouseclicked (mouseevent e) {
27.}
28.
29.public void mouseentered (mouseevent e) {
30.String s = "the mouse entred";
31.tf.settext (s);
32.}
Complex example (continued)
1.public void mouseexited (mouseevent e) {2.string s = "the mouse has left the building";
3.Tf.setText (s);
4.}
5.
6.public void mousepressed (mouseevent e) {
7.}
8.
9.public void mouseeleased (mouseevent e) {
10.}
11.}
Some places in this example are worth noting. They will be discussed in the following sections.
Define multiple interfaces
This class is declared by the following code in line 4:
Implements MouseMotionListener, MouseListener
When you declare multiple interfaces, you can separate them with a comma.
Monitor multiple sources
If you are in line 11 and 12, the following methods are called:
Both types of events cause the method in the Twolisten class being called. An object can "listen" any number of event sources; its class only needs to implement the required interface.
F.Addmouselistener (this);
F.AddmouseMotionListener (this);
Complex example (continued)
Get detail about events
Call the processor method (such as mouseDragged ()), the event parameters belt may contain important information about the source event. To determine which details about certain types of events, you should check the appropriate class documents in the java.awt.event package.
9.5.3 Many listeners
Multi-listener
- Multiple listeners can make the same action in the unrelated part of a program.
- When an event occurs, all registered listeners' processors are called
The AWT event listener framework is in fact allowing the same component with multiple listeners. Generally, if you want to write a program, it performs multiple actions based on an event, and write those behavior to the processor. However, sometimes a program is designed to require a number of unrelated parts of the same program to respond to the same event. This situation is possible, for example, adding a context-sensitive help system to an existing program.
The listener mechanism allows you to call the AddXxxListener method multiple times, and you can specify any multiple different listeners based on your design. When an event occurs, all the registered listeners' processors are called.
Note - There is no order in which the event processor method is called. Typically, if the order in which the call is called, the processor is not unrelated. In this case, only the first listener is registered, and other listeners are called directly.
9.5.4 Event Adapters (Adapter)
Your defined Listener can inherit the Adapter class and only rewrite the methods you need. E.g:
It is very large, especially the MouseListener interface and the ComponentListener interface.
Take the mouselistener interface as an example, it defines the following method:
- mouseclicked (mouseevent)
- mouseentered (mouseevent)
- MouseExited (MouseEvent)
- MousePressed (MouseEvent)
- mouseeleased (mouseevent)
For convenience, Java language provides an Adapters class that implements classes with multiple methods. The method in these Adapters classes is empty.
You can inherit the Adapters class, and you only need to rewrite the methods you need. E.g:
1. IMPORT JAVA.AWT. *;
2. IMPORT JAVA.AWT.EVENT. *;
3.
4.Public class mouseclickhandler extends mouseadapter {
5.
6./ We Just Need The Mouseclick Handler, SO We Use
7./ The adapter to avoid hoving to write all the
8.// Event Handler Methods
9.public void mouseclicked (mouseevent e) {
10.// do something with the mouse click ...
11.}
12.}
9.5.5 Anonymous class
You can include the definition of the entire class in a domain in an expression. This method defines a so-called anonymous class and creates an instance immediately. Anonymous class is usually used with AWT event processing. E.g:
1. IMPORT JAVA.AWT. *;
2. IMPORT JAVA.AWT.EVENT. *;
3.public class anontest {
4.Private frame f;
5.Private TextField TF;
6.
7.public static void main (string args [])
8.{
9.ontest obj = new anontest ();
10.obj.go ();
11.}
12.
Anonymous class (continued)
1.public void Go () {
2.F = New frame ("anonymous classes example");
3.F.Add (New Label ("Click and Drag THE"
4. "Mouse", BorderLayout.North);
5.TF = New TextField (30);
6.f.add (TF, BorderLayout.South);
7.
8.f.addmouseMotionListener (New
9.MouseMotionAdapter () {
10.Public void mousedraged (mouseevent e) {
11.String s =
12. "Mouse Dragging: x =" E.GETX ()
13. "y =" E.GETY ();
14.Tf.setText (s);
15.}
16.}); // <- Note The Closing Parenthesis
17.
18.f.addmouselistener (new mouseclickhandler ());
19.f.setsize (300, 200);
20.f.setvisible (TRUE);
twenty one.}
twenty two.}
Exercise: event
Exercise Goals - You will write, compile and run the modified version of the Calculator graphical user interface and the Account graphical user interface with the event processor.
First, ready
In order to complete this exercise very well, you must have a clear understanding of how the event model works.
Second, the task
Level 1: Create a Calculator graphical user interface, the second part
1. Use the graphical user interface code created in the module 8, write a segment of event code to connect to the user interface of the calculator and the event processor on the process of the function on the calculator.
Horizontal 3: Create an Account graphical user interface, the second part
1. Create an AccountEvent class, which is activated when an object is changed at an account. Then activate the event to the BankManager class. Practice based on the Teller.java GUI code you created in the module 8.
Third, practice summary
Discuss - spend a few minutes to discuss, you have experienced, and what you have found in this experimental exercise process. Experience explanation summary application
Fourth, check your progress
Before entering the next module, please confirm that you can:
- Write code to handle events that occur in the graphical user interface
- Describe the concept of Adapter class, including how to use them
- Determine user action generated by the event based on the details of the event object
- Create a suitable interface and event processor for various types of events.
V. Thinking
You now know how to create a Java graphical user interface for graphical output and interactive user input. However, we only introduce some components that can create a graphical user interface. What is the use of other components in the graphical user interface?