1. Event handling
In fact, the name of event processing is naturally thought of the message response mechanism in MFC. As far as I understand, they should be considered as the situation of southern oranges and northern citrus. I suspect that the "new bottle" of event processing in Java should be the message response in MFC.
The so-called "events" are changes such as keyboard keys, mouse clicks, etc. that cause a certain state to change due to actions or what needs to be responded to accordingly. We can divide events in Java into several categories: buttons, mouse, keyboard, window, and other events.
Event processing model
1. Inherited event processing model (JDK1.0)
In JDK1.0, event processing is based on inheritance. Events are sent to the component first and then propagated upward along the container level. Events that are not processed by the component will automatically continue to propagate to the component's container. --This seems to be consistent with the original event response order or polymorphic response mechanism in MFC, and the proxy-based event processing mechanism mentioned later seems to be consistent with the MFC callback mechanism.
Specific treatment methods
Call the action() method or handleEvent() method to get the events that occur when the program is running, and all events that occur in the component are handled in this method.
2. Agent-based event processing model (JDK1.1)
In this model, events are sent directly to the component that produces this event.
For each component, one or more classes called listeners are registered, which contain event handlers that receive and process this event.
The listener is a class that implements the Listener interface. Events are objects reported only to registered listeners. Each event has a corresponding listener interface.
When clicking on the Button object with the mouse, an ActionEvent event will be sent. This ActionEvent event will be received by the actionPerformed() method of all ActionListener registered using the addActionListener() method.
Features of the agent-based event processing model ① Events will not be processed unexpectedly. In a hierarchical model, an event may propagate to the container and be processed at an unexpected level.
② It is possible to create and use the adapter class to classify event actions.
③It is conducive to distributing work to various categories.
Focus on learning this event processing model
3. Events
Three elements of event processing.
(1) Event Source The event source is the generator of an event, such as buttons, windows and text fields.
(2) Event type All events in Java are encapsulated into a class, and these event classes are concentrated in the java.awt.event package. All event classes inherit the AWTEvent class and a method - getSouce() method, which returns the object where the event occurred.
(3) After different types of events occur in the event listener, the event listener receives the event and calls the corresponding event processing method. All event listeners are actually an interface in the java.awt.event package, introducing the java.util.EventListener interface. Listeners of different event types have different methods.
Event processing steps ① The program adds the java.awt.event package:
Import java.awt.event;
② Register an event listener for the required event source object:
Event source object.addXXXListener(XXXListener);
③ Implement the corresponding method. If a listener interface contains multiple methods, you need to implement all method examples: b2.addActionListener(this)
4. Event Adapters (adapter)
The workload of implementing all methods of each Listener interface is very high. For convenience, the Java language provides the Adapters class to implement classes containing multiple methods.
The Listener you define can inherit the Adapter class and just override the methods you need.
For example, the listener corresponding to the window event is WindowListener, which must implement multiple methods, including windowOpened(), windowClosed(), windowClosing(), WindowIconfied(), WindowDeiconfied(), WindowActivated(), and WindowDeactivated(), which increases unnecessary programming workload.
If you inherit WindowAdapter, you only need to implement one or several of the methods, and you do not need to implement all methods. Many of the following examples only implement one method of windowClosing(), with the purpose of exiting the system when closing the window.
4.1 Handling of button events
The event that occurs when clicking the button is an action event. The event class corresponding to the action event is the ActionEvent class. The event listener corresponding to the action event is: ActionListener
The main methods of listeners:
actionPerformed(ActionEvent e) The operation project that is called when an action event occurs:
The first step is to register the action event listener addActionListener(ActionListener).
The second step is to implement the ActionListener interface method: actionPerformed(ActionEvent e)
4.2 Handling of mouse events
The event source that triggers a mouse event is usually a container. When the mouse enters or leaves the container, or clicks the mouse, drags the mouse, etc. in the container, the mouse event will occur. The event class corresponding to the mouse event is the MouseEvent class.
Methods in MouseEvent class:
getX() gets the X coordinate of the mouse
getY() gets the Y coordinate of the mouse
getPoint() gets the mouse position and the mouse event corresponds to two event listeners: MouseListener (or MouseAdapter) corresponds to the mouse event, and MouseMotionListener (or MouseMotionAdapter) corresponds to the mouse movement event.
The main method of MouseListener (or MouseAdapter)
MousePressed(MouseEvent e) How to deal with mouse pressing
MouseReleased(MouseEvent e) How to handle mouse release
MouseEntered(MouseEvent e) How to handle the mouse when entering
MouseExited(MouseEvent e) How to deal with the mouse when leaving
MouseClicked(MouseEvent e) How to deal with mouse clicking
The main method of MouseMotionListener (or MouseMotionAdapter)
MouseMoved(MouseEvent e) How to handle the mouse when moving
MouseDraged(MouseEvent e) How to handle mouse dragging
4.3 Handling of keyboard events
When pressing or releasing the keyboard in a component with keyboard focus, keyboard events occur. The event class corresponding to the keyboard event is the KeyEvent class
KeyEvent class main methods:
getKeyCode() gets the key code to be pressed or released
getKeyText() gets the string of the key pressed or released. The event listener corresponding to the keyboard event is: KeyListener or KeyAdapter
Main methods:
KeyPressed(KeyEvent e) How to handle when pressing the keyboard
KeyReleased(KeyEvent e) How to handle the keyboard when releasing it
4.4 Handling of window events
Only if there are Window and its extended classes (Frame, Dialog), etc., can window events be triggered, indicating that the window is in an active/invalid state, icon/non-icon state, or open/close state, etc. The corresponding class is WindowEvent, and the listener is WindowListener (or WindowAdapter)
Main methods:
windowOpened(WindowEvent e) event handling of opening window
windowClosed(WindowEvent e) Event handling of closing window
windowClosing (WindowEvent e) closing event processing of window
Event handling of WindowActivated(WindowEvent e) activation status
Event handling of invalid status of WindowDeactivated(WindowEvent e)
4.5 Handling of other events
4.5.1 The event class for check box and radio button event processing is ItemEvent:
The event listener corresponding to the option event is: ItemListener
method:
itemStateChanged (ItemEvent e) is called when the option event occurs 4.5.2 The event class corresponding to the scrollbar event processing adjustment event is the AdjustmentEvent class:
The event listener corresponding to the adjustment event is: AdjustmentListener
method:
adjustmentValueChanged (AdjustmentEvent e) is called when adjustment event occurs
4.5.3 The event processing event class in the drop-down list is ItemEvent:
The event listener corresponding to the option event is: ItemListener
method:
itemStateChanged (ItemEvent e) is called when an action occurs in the drop-down list
(It can be seen that the event processing of the drop-down list is the same as the event type, event listener and method, as the event processing of the check box, the event type, event listener and method of the event processing of the radio box)
4.5.4 Handling of menu events Menu events is generally an event that occurs when we click on a menu item.
There are two types of menu items:
MenuItem Action Event
CheckboxMenuItem, option event
The first step in the event processing of MenuItem is to register the action event listener addActionListener(ActionListener) for all MenuItem menu items.
The second step is to implement the method of ActionListener interface: actionPerformed(ActionEvent e). In this method, use e.getSource() to obtain the menu item selected by the user and perform corresponding processing.
The first step in the event handling of CheckboxMenuItem is to register the option event listener for all CheckMenuItem menu items to addItemListener(ItemListener).
The second step is to implement the ItemListener interface method: itemStateChanged(ItemEvent e). In this method, use e.getSource() to get the menu item selected by the user, e.getItem() to get the label of the menu item selected by the user, and e.getStateChange() to get whether it is selected and perform corresponding processing.
2. Exception handling
No good programming language or programmer will ignore the handling of exceptions. As a popular object-oriented programming language, Java, the exception handling mechanism is naturally one of its important features.
Generally speaking, exceptions are described as: errors in programming. However, in fact, this error is very frequent, with many kinds, such as: compilation errors and operation errors (specifically, it is divided into: system operation errors and logical operation errors. What system operation errors are rarely considered as programming errors, before.)
In JAVA, an exception is a class that inherits from the Throwable class. Each exception class represents a run error (note: it is a run error). The exception class contains information about the operation error and the method of handling the error.
Java exception handling mechanism:
Whenever an identifiable running error occurs during the Java program operation, (that is, when the error has an exception class corresponding to it), the system will generate a corresponding object of the exception class (note: it is called generating an exception class object.) that is, an exception is generated.
Once an exception object is generated, there must be a corresponding mechanism in the system to handle it to ensure that there will be no crashes, dead loops or other damage to the operating system, thus ensuring the security of the operation of the entire program.
Exception and exception classes:
Error: Generated and thrown by the Java virtual machine, and the Java program does not handle it.
Runtime Exception (system errors such as 0, array subscripts exceed the range): Detected by the system, the user's Java program can not be processed, and the system handed them to the default exception handler (note: there is a default exception handling).
Exception (problems in the program, predictable): The Java compiler requires that the Java program must catch or declare all non-runtime exceptions that users generate their own exceptions.
Exception class constructor:
public Exception();
public Exception(String s); can accept information passed in by string parameters, which is usually a description of the error corresponding to the exception.
The Exception class also inherits several methods from the father Throwable, among which the commonly used ones are:
1) public String toString();
The toString() method returns a string describing the current Exception class information.
2) public void printStackTrace();
printStackTrace() method has no return value. Its function is to complete a printing operation and print out the stack usage track of the current exception object on the current standard output (usually the screen), that is, the program calls which objects or classes to execute, which methods of the exception object are generated during the operation.
System-defined operation exception
Some of these subclasses are defined in advance by the system and included in the Java class library, and are called system-defined operation exceptions
User-defined exceptions
For operation errors unique to a certain application, programmers need to create user-defined exception classes and exception objects in the user program according to the special logic of the program. User-defined exceptions are usually used as the parent class of the exception class. However, there is a problem that has not been understood yet: How do the system know that an error occurs and it is recognizable? How to generate corresponding exception class objects? How do you know how to solve the exception class object by using the corresponding method? Does each exception class object that handles the corresponding exception have only one exception handling method? ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――�
When creating user-defined exceptions, the following tasks are generally required:
1) Declare a new exception class, so that it takes the Exception class or other existing system exception class or user exception as the parent class.
2) Define attributes and methods for the new exception class, or overload the attributes and methods of the parent class so that these attributes and methods can reflect the error information corresponding to the class.
Exception thrown
If a Java program raises an identifiable error when it is run, it will generate an object of the exception class corresponding to the error. This process is called exception throwing.
It is actually throwing an instance of the corresponding exception class object.
Depending on the exception class, there are two ways to throw exceptions: system automatic throwing and user throwing:
1. The system will automatically throw it out
The system defined operation error exceptions are automatically thrown by the system.
2. User throws
User-defined exceptions cannot be automatically thrown by the system, but must be thrown by the user in Java statements. In Java statements, the throw statement is used to explicitly throw an "exception".
Return type method name (parameter list) in the format throws throws list of exception class names to be thrown {
…
throw exception class instance; //Note here...
}
Notice:
1) Generally, an exception is thrown when a certain condition is met in the program;
Often put the throw statement in the if branch of the if statement,
if(I>100)
throw (new MyException());
2) For methods containing throw statements, the following parts should be added to the method header definition:
throws The list of exception class names to be thrown. This is mainly to inform the upper method to call this method, and to prepare to accept and handle exceptions it may throw during runtime. If there is more than one throw statement in the method, all possible exceptions should be listed in the method header throws.
3) The Java language requires that all classes declared with the throws keyword and objects thrown with throw must be Throwable class or its subclass. If you try to throw an object that is not throwable, the Java compiler will report an error exception:
Mainly consider how to catch exceptions, how to jump after catching exceptions, and how to write exception handling statements
1. try…catch… finally block
1) try
The {} in the try statement contains a piece of program code that may throw one or more exceptions. These codes actually specify the range of exceptions that can be caught by the catch block after it.
If an exception occurs when a Java program runs into a statement in a try block, it no longer continues to execute other statements in the try block, but directly enters the catch block to find the first matching exception type and process it.
2) catch block
The parameters of the catch statement are similar to the definition of a method, including an exception type and an exception object.
The exception type must be a subclass of the Throwable class, which specifies the exception type handled by the catch statement;
The exception object is the method code for handling the exception object in the curly braces thrown by the Java runtime system in the program code block specified by the try.
There can be multiple catch statements that handle different types of exceptions separately.
The Java runtime system detects the exception type processed by each catch statement from top to bottom, until it finds a catch statement that matches it.
Here, type matching means that the exception type in catch is exactly the same as the type of the generated exception object or the parent class of the exception object. Therefore, the sorting order of the catch statement should be from special to general. (Think about why?)
3) Finally block
The finally statement can be said to be a cleanup mechanism provided for exception handling events. It is generally used to close files or release other system resources. The try-catch-finally statement may have a statement with a finally part.
If there is no finally part, when the program code specified by try throws an exception, other program codes will not be executed;
If there is a finally part, no matter whether an exception occurs in the try block or whether a catch part has been executed, the finally part statement must be executed.
It can be seen that the finally part of the statement provides a unified exit for exception handling.
Multiple exceptions can produce multiple different exceptions, and if you want to take different methods to deal with these exceptions, you need to use a multi exception handling mechanism.
Multiple exception processing is achieved by defining several catch blocks after a try block. Each catch block is used to receive and process a specific exception object. Through the parameters of the catch block, it determines whether an exception object should be an exception received and processed by this catch block.
Which catch block is obtained? According to the matching of the exception parameters of the exception object and the catch block: When they meet any of the following three conditions, the exception object and the parameter are considered to match:
1) The exception object belongs to the same exception class as the parameter.
2) The exception object belongs to a subclass of the parameter exception class.
3) The exception object implements the interface defined by the parameters.
If the exception object generated by the try block is received by the first catch block, the program's flow will directly jump to this catch statement block. After the statement block is executed, the current method will be exited. Statements that have not been executed in the try block and other catch blocks will be ignored. If the exception object generated by the try block does not match the first catch block, the system will automatically go to the second catch block for matching. If the second still does not match, it will turn to the third, fourth... until a catch block that can receive the exception object is found, and the process will be completed.
If the exception object generated by the try block is received by the first catch block, the program's flow will directly jump to this catch statement block. After the statement block is executed, the current method will be exited. Statements that have not been executed in the try block and other catch blocks will be ignored. If the exception object generated by the try block does not match the first catch block, the system will automatically go to the second catch block for matching. If the second still does not match, it will turn to the third, fourth... until a catch block that can receive the exception object is found, and the process will be completed.
If the execution of all statements in the try block does not raise an exception, all catch blocks will be ignored and not executed.
Notice:
1) The statements in the catch block should perform different operations according to the different exceptions, so when dealing with multiple exceptions, you should pay attention to carefully design the arrangement order of each catch block. Generally, catch blocks that deal with more specific and common exceptions should be placed in front, while catch blocks that can match multiple exceptions should be placed in the back.
/*Try the user to run the error exception handling: The problem is this. When the initial value of the entered user's salary is less than 800, it is wrong. Of course, if the change in salary exceeds 20%, it is also wrong*/ import java.awt.*; import java.applet.*; import java.awt.event.*; public class UserExceptionApplet extends Applet implements ActionListener{ Label prompt1=new Label("Please enter the employee's name and initial value of salary:"); Label prompt2=new Label("Please enter the salary to be modified"); TextField name,isal,nsal; String msg; Employee Emp; Button okBtn=new Button("OK"); Button cancelBtn=new Button("Cancel"); public void init(){ name=new TextField(5); isal=new TextField(5); nsal=new TextField(5); add(prompt1); add(name); add(isal); add(prompt2); add(nsal); add(okBtn); okBtn.addActionListener(this); cancelBtn.addActionListener(this); add(cancelBtn); } public void paint(Graphics g){ g.drawString(msg,0,80); } public void CreateEmp(String empName,double sa){ try{ Emp=new Employee(empName,sa); msg=new String(Emp.toString()); } catch(IllegalSalaryException is){ msg=new String(ise.toString()); } } public void ChangeEmpSal(double changeSal){ try{ Emp.setEmpSalary(changeSal); msg=new String(Emp.toString()); } catch(IllegalSalaryException illSal){ msg=new String(illSal.toString()); } catch(IllegalSalaryChangeException illSalChange){ msg=new String(Emp.toString()+illSalChange.toString()); } } public void actionPerformed(ActionEvent e){ String empName; double empSal,changeSal; Object obj=e.getSource(); if(obj==okBtn){ empName=new String(name.getText()); if(empName==null){ msg=new String("Please enter the employee's name and salary first and create it"); } if(nsal.getText()==null){ empSal=Double.valueOf(isal.getText()).doubleValue(); CreateEmp(empName,empSal); } else{ changeSal=Double.valueOf(nsal.getText()).doubleValue(); ChangeEmpSal(changeSal); } } if(obj==cancelBtn){ naem.setText(""); isal.setText(""); nsal.setText(""); } repaint(); } } class Employee{ String m_EmpName; double m_EmpSalary; Employee(String name,double initial)throws IllegalSalaryException{ m_EmpName=name;//See if there is any problem here, the reference code is m_EmpName=new String(name); if(initsalary<800){ throw(new IllegalSalaryException(this,initsalary));//throw statement} m_EmpSalary=initsalary; } public String getEmpName(){ return m_EmpName; } public double getEmpSalary(){ return m_EmpSalary; } public boolean setEmpSalary(double newSal) throws IllegalSalaryException,IllegalSalaryChangeException{ if(newSal<800) throw(new IllegalSalaryException(this,newSal)); else if(getEmpSalary()==0.0){ m_EmpSalary=newSal; return true; } else if(Math.abs(newSal-getEmpSalary())/getEmpSalary()>=0.2) throw(new IllegalSalaryChangeException(this,newSal-getEmpSalary())); else{ m_EmpSalary=newSal; return true; } } public String toString(){ String s; s="Name:"+m_EmpName+"Salary: "+m_EmpSalary; return s; } } class IllegalSalaryException extends Exception{ private Employee m_ConcernedEmp; private double m_IllegalSalary; IllegalSalaryException(Employee emp,double isal){ super("Wage is lower than minimum wage"); m_ConcernedEmp=emp; m_IllegalSalary=isal; } public String toString(){ String s; s="The wages provided to employees are illegal: Employees:"+m_ConcernedEmp.getEmpName()+"Illegal salary:"+m_IllegalSalary+"lower than minimum wage amount of RMB 800"; return s; } } class IllegalSalaryChangeException extends Exception{ private Employee m_ConcernedEmp; private double m_IllegalSalaryChange; IllegalSalaryChangeException(Employee emp,double csal){ super("Salary change is too large"); m_ConcernedEmp=emp; m_IllegalSalaryChange=csal; } public String toString(){ String s; s="The wage change provided to employees is illegal: Employee:"+m_ConcernedEmp.getEmpName()+"Illegal change of wage change:"+m_IllegalSalaryChange+"20% higher than the original salary"; return s; } }