1. Event processing
In fact, the name event processing naturally reminds me of the message response mechanism in MFC. From my experience, they should be regarded as the situation of Nanjubeizhi. I suspect event processing in Java This "new bottle" should be the message in MFC that responds to this "old wine".
The so-called "events" are changes such as keyboard keys, mouse clicks, etc. that are caused by actions or something that cause a state change and require a corresponding response to this change. We can divide events in Java into several categories: button, mouse, keyboard, window, and other events.
Event processing model
1. Inheritance-based event processing model (JDK1.0)
In JDK1.0, event processing is based on inheritance. Events are first sent to components and then propagated upward along the container hierarchy. Events that are not handled by a component are automatically propagated to the component's container. ——This seems to be consistent with the original event response sequence or polymorphic response mechanism in MFC, and the agent-based event processing mechanism mentioned later seems to be consistent with MFC's callback mechanism.
Specific processing method
Call the action() method or handleEvent() method to obtain events that occur when the program is running. Events that occur in all components are processed in this method.
2. Agent-based event processing model (JDK1.1)
In this model, events are sent directly to the component that generates the event.
For each component, register one or more called listeners These classes contain event handlers that receive and process the event.
The listener is a class that implements the Listener interface. Events are objects that are reported only to registered listeners. Each event has a corresponding listener interface.
When you click with the mouse on the Button object, an ActionEvent event will be sent. This ActionEvent event will be received by the actionPerformed() method of all ActionListeners registered using the addActionListener() method.
Characteristics of the agent-based event processing model
①Events will not be processed accidentally. In the hierarchical model, an event may propagate to the container and be handled at an unexpected level.
②It is possible to create and use adapter classes to classify event actions.
③It is helpful to distribute work into various categories.
Focus on learning this event processing model
3. Events
The three elements of event processing.
(1) Event source Event source is the generator of an event, such as buttons, windows, text fields, etc.
(2) Event type All events in Java are encapsulated into a class. These event classes are concentrated in the java.awt.event package. All event classes inherit the AWTEvent class and a method-getSouce() method. , this method returns the object where the event occurred.
(3) Event listener After different types of events occur, the event listener receives the event and calls the corresponding event processing method. All event listeners are actually interfaces in the java.awt.event package, which introduces the java.util.EventListener interface. Listeners for different event types have different methods.
Event processing steps
① Add the program to 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 methods
Example: b2.addActionListener(this)
4. Event Adapters(Adapters)
Implement all methods of each Listener interface The workload is very large. For convenience, the Java language provides the Adapters class to implement classes with multiple methods.
The Listener you define can inherit the Adapter class and only need to 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(), WindowDeactivated(), This increases unnecessary programming workload.
If you inherit WindowAdapter, you only need to implement one or a few methods, not all methods. Many of the following examples only implement the windowClosing() method, with the purpose of exiting the system when the window is closed.
4.1 Processing of button events
The event that occurs when a button is clicked 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 method of the listener:
actionPerformed(ActionEvent e) is called when an action event occurs
Implement the operation project of the action event:
The first step is to register the action event listener addActionListener(ActionListener).
The second step is to implement the method of ActionListener interface: actionPerformed(ActionEvent e)
4.2 Mouse event processing
The event source that triggers mouse events is usually a container. When the mouse enters or leaves the container, or when the mouse is clicked or dragged in the container, a mouse event occurs
The event class corresponding to the mouse event is the MouseEvent class
Methods in the MouseEvent class:
getX() gets the X coordinate of the mouse
getY() gets the Y coordinate of the mouse
getPoint() gets the position of the mouse
The event listeners corresponding to mouse events are Two: MouseListener (or MouseAdapter) corresponds to mouse events, and MouseMotionListener (or MouseMotionAdapter) corresponds to mouse movement events.
Main methods of MouseListener (or MouseAdapter)
MousePressed(MouseEvent e) Processing method when mouse is pressed
MouseReleased(MouseEvent e) Processing method when mouse is released
MouseEntered(MouseEvent e) Mouse enters Processing method when the mouse leaves
MouseExited(MouseEvent e) Processing method when the mouse leaves
MouseClicked(MouseEvent e) Processing method when the mouse clicks
The main method of MouseMotionListener (or MouseMotionAdapter)
MouseMoved(MouseEvent e) Processing method when the mouse is moved
MouseDraged(MouseEvent e) Processing method when the mouse is dragged
4.3 Processing of keyboard events
Keyboard events occur when the keyboard is pressed or released in a component with keyboard focus
The event class corresponding to the keyboard event is the KeyEvent class
The main method of the KeyEvent class:
GetKeyCode() The key code that is pressed or released
getKeyText() gets the string of the key that is pressed or released
The event listener corresponding to the keyboard event is: KeyListener or KeyAdapter
Main method:
KeyPressed(KeyEvent e) Processing method when the keyboard is pressed
Processing method when the keyboard is released KeyReleased(KeyEvent e)
4.4 Processing of window events
Can only be triggered by Window and its extended classes (Frame, Dialog), etc. Window events, indicating that the window is in active/invalid state, icon/non-icon state, or open/closed state, etc.
The class corresponding to the window event is WindowEvent, and the listener is WindowListener (or WindowAdapter)
Main method:
WindowOPENED (WindowEvent E) Event processing of opening the window
WindowClosed (Windowevent E) The event processing of the window is closed
WindowClosing (Windowevent E) is being closed the window. D (WindowEvent E) Event processing of the activation state
WindowDeactivated (Windowevent E) Event processing of invalid status
4.5 The processing of other events
4.5.1 check box, single -selection button event processing
event category is Itemvent:
Option event event corresponding The event listener is: ItemListener
Method:
itemStateChanged (ItemEvent e) is called when an option event occurs
4.5.2 Scroll bar event processing
The event class corresponding to the adjustment event is the AdjustmentEvent class:
The event listener corresponding to the adjustment event is: AdjustmentListener
Method:
adjustmentValueChanged (AdjustmentEvent e) is called when an adjustment event occurs
4.5.3 Event processing of the drop-down list
The event class 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 and event type of the drop-down list, The event listeners and methods are the same as the event types, event listeners and methods of check box and radio button event processing)
4.5.4 Menu event processing
Menu events are generally when we click on a menu events that occurred during the item.
There are two types of menu items:
MenuItem action event
CheckboxMenuItem, option event
MenuItem event processing
The first step 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.
CheckboxMenuItem event processing
The first step is to register the option event listener addItemListener (ItemListener) for all CheckMenuItem menu items.
The second step is to implement the method of the ItemListener interface: 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
Any good programming language and programmers will not 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, when explaining exceptions, they are said to be errors in programming. However, in fact, this error is very frequent, and there are many kinds, such as: compilation error, operation error (specifically, it is divided into: system operation error and logical operation error. This kind of system operation error, I rarely count it as It's a mistake in programming, before. )
In JAVA, exception is a class, which inherits from Throwable class. Each exception class represents a runtime error (note: it is a runtime error). The exception class contains information about the running error and error handling methods.
Java’s exception handling mechanism:
Whenever a recognizable running error occurs during the running of a Java program (that is, when the error has an exception class corresponding to it), the system will generate a corresponding exception. An object of the exception class (note: it is called generating an exception class object.) means generating an exception.
Once an exception object is generated, there must be a corresponding mechanism in the system to handle it to ensure that no crashes, infinite loops or other damage to the operating system will occur, thus ensuring the safety of the entire program.
Exceptions and exception classes:
Error: generated and thrown by the Java virtual machine, and not processed by the Java program.
Runtime Exception (system errors such as division by 0, array subscript out of range): detected by the system, The user's Java programs do not need to be processed, and the system will hand them over to the default exception handler (note: there is default exception handling).
Exception (problems in the program, foreseeable): The Java compiler requires Java The program must capture or declare all non-runtime exceptions
User-generated exceptions
Exception class
Constructor:
public Exception();
public Exception(String s); can accept characters The information passed in as a string parameter is usually a description of the error corresponding to the exception.
The Exception class also inherits several methods from its 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();
The printStackTrace() method has no return value. Its function is to complete a printing operation and print out the stack usage of the current exception object on the current standard output (usually the screen). The trajectory, that is, which methods of objects or classes are called and executed by the program successively, causing this exception object to be generated during the running process.
System-defined running exceptions
Some of these subclasses are pre-defined by the system and included in the Java class library, called system-defined running exceptions
User-defined exceptions
For a certain Application-specific running errors require programmers to create user-defined exception classes and exception objects in the user program according to the special logic of the program
User-defined exceptions usually use Exception as the parent class of the exception class
But there is a question that is not yet understood: when an error occurs, how does the system know that it is recognized? How to generate the corresponding exception class object? How does an exception object know to use the corresponding method to solve it? Is there only one exception handling method for each exception class object that handles the corresponding exception? ————————————It turns out that user-defined exceptions are thrown through the statement throw.
When creating a user-defined exception, you generally need to complete the following work:
1) Declare a new exception class, making it use the Exception class or other existing system exception class or user exception as the parent class .
2) Define properties and methods for the new exception class, or overload the properties and methods of the parent class so that these properties and methods can reflect the error information corresponding to the class.
Exception throwing
If a Java program triggers an identifiable error while running, it will generate an object of the exception class corresponding to the error. This process is called exception throwing,
Actually, it is the throw of an instance of the corresponding exception class object.
Depending on the exception type, there are two ways to throw exceptions: automatically thrown by the system and thrown by the user:
1. Automatically thrown by the system
The system-defined running error exceptions used are all thrown by the system. Automatically throw
2. User-defined exceptions cannot be thrown automatically by the system, but must be thrown by the user using Java statements. In Java statements, the throw statement is used to explicitly throw Throw an "exception"
The format thrown using the throw statement
Return type method name (parameter list) throws List of exception class names to be thrown {
1) Generally, an exception is thrown when a certain condition is met in the program;
Often the throw statement is placed in the if branch of the if statement,
; The upper-layer method is prepared to accept and handle the exceptions it may throw during operation
If there is more than one throw statement in the method, all possible exceptions should be listed in the method header throws
3) Java language It is required that all classes declared with the throws keyword and objects thrown with throw must be Throwable classes or their subclasses. If you try to throw an object that is not throwable (Throwable), the Java compiler will report an error
Exception handling:
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 { } of the try statement contains a piece of program code that may throw one or more exceptions
These codes actually specify the catch behind it The range of exceptions that the block can catch.
If an exception occurs when the Java program runs to the statement in the try block, it will no longer continue to execute other statements in the try block, but directly enter the catch block to find the first matching exception type and execute it. deal with.
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 thrown by the Java runtime system in the curly brackets in the program code block specified by try Contains method code for handling exception objects.
There can be multiple catch statements to handle different types of exceptions respectively.
The Java runtime system detects the exception type handled by each catch statement from top to bottom until a matching catch statement is found.
Here, type matching means that the exception type in the catch is completely consistent with the type of the generated exception object or is the parent class of the exception object. Therefore, the sorting order of the catch statement should be from special to general. (Consider why?)
3) Finally block
The finally statement can be said to be a cleanup mechanism for exception handling events. It is generally used to close files or release other system resources
In the try-catch-finally statement There can be no finally part of the statement.
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, whether After executing the statement in the catch part, the statement in the finally part must be executed.
It can be seen that the finally part of the statement provides a unified exit for exception handling.
Multiple exception handling
A try block may generate a variety of different exceptions. If you want to use different methods to handle these exceptions, you need to use a multiple exception handling mechanism.
Multiple exception handling is achieved by defining several catch blocks after a try block. Each catch block is used to receive and process a specific exception object.
Judge an exception object through the parameters of the catch block. Whether exceptions should be received and handled by this catch block.
Which catch block is obtained, based on the matching of the exception object and the exception parameters of the catch block: when they meet any of the following three conditions, the exception object and parameters are considered to match:
1) Exception object and parameters Belong to the same exception class.
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 flow will jump directly to this catch statement block. After the statement block is executed, the current method will exit. statement 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 one still does not match, it will Go to the third, fourth... until you find a catch block that can receive the exception object, and complete the process jump.
If the exception object generated by the try block is received by the first catch block, the program flow will jump directly to this catch statement block. After the statement block is executed, the current method will exit. Statement 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 one still does not match, it will Go to the third, fourth... until you find a catch block that can receive the exception object, and complete the process jump.
If the execution of all statements in the try block does not cause an exception, all catch blocks will be ignored and not executed.
Note:
1) The statements in the catch block should perform different operations according to different exceptions
Therefore, when handling multiple exceptions, attention should be paid to carefully designing the order of each catch block. Generally, catch blocks that handle more specific and common exceptions should be placed at the front, while catch blocks that can match multiple exceptions should be placed at the back.
/*尝试用户运行错误的异常处理: 问题是这样的,当输入的用户工资初值少于800则是错误的,当然工资的变化如果超过20%,则也是错误的 */ import java.awt.*; import java.applet.*; import java.awt.event.*; public class UserExceptionApplet extends Applet implements ActionListener{ Label prompt1=new Label("请输入雇员姓名和工资初值:"); Label prompt2=new Label("请输入欲修改的工资"); 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 ise){ 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("请先输入雇员姓名工资并创建之"); } 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 initsalary)throws IllegalSalaryException{ m_EmpName=name;//看这里有问题没,参考代码为m_EmpName=new String(name); if(initsalary<800){ throw(new IllegalSalaryException(this,initsalary));//throw语句 } 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="姓名:"+m_EmpName+"工资: "+m_EmpSalary; return s; } } class IllegalSalaryException extends Exception{ private Employee m_ConcernedEmp; private double m_IllegalSalary; IllegalSalaryException(Employee emp,double isal){ super("工资低于最低工资"); m_ConcernedEmp=emp; m_IllegalSalary=isal; } public String toString(){ String s; s="为雇员提供的工资不合法:雇员:"+m_ConcernedEmp.getEmpName()+"非法工资:"+m_IllegalSalary+"低于最低工资数额800元"; return s; } } class IllegalSalaryChangeException extends Exception{ private Employee m_ConcernedEmp; private double m_IllegalSalaryChange; IllegalSalaryChangeException(Employee emp,double csal){ super("工资变动太大"); m_ConcernedEmp=emp; m_IllegalSalaryChange=csal; } public String toString(){ String s; s="为雇员提供的工资变动不合法:雇员:"+m_ConcernedEmp.getEmpName()+"非法变动工资变化:"+m_IllegalSalaryChange+"高于原工资的20%"; return s; } }
For more articles analyzing event processing and exception handling mechanisms in Java, please pay attention to the PHP Chinese website!