Parsing the event handling and exception handling mechanism in Java _java

Source: Internet
Author: User
Tags event listener exception handling finally block gettext inheritance throw exception throwable

I. Event handling
In fact, by the event processing this name naturally think of MFC in the message response mechanism, in my experience, they should be regarded as the southern Orange case, I suspect that the incident in Java processing this "new bottle" should be installed in the MFC message response to this "old wine."
So-called "events" such as keyboard keys, mouse clicks, such as the movement or what caused a state to change and need to respond to this change in response to such changes. We can divide the events in Java into buttons, mice, keyboards, windows, other events, and other major categories.
Event Handling Model
1. An inheritance based event processing model (JDK1.0)
In JDK1.0, event handling is based on inheritance, the event is first sent to the component, and then propagated up the container hierarchy. Events that are not handled by the component automatically continue to propagate to the container of the component. This is consistent with the original event response sequence or polymorphic response mechanism in MFC, and the subsequent agent-based event-handling mechanism seems to be consistent with the MFC callback mechanism.
the specific processing method
Call the action () method or the Handleevent () method to get the event that occurs when the program is running, and the events that occur in all components are handled in this method.
2, agent-based event handling Model (JDK1). 1)
In this model, the event is sent directly to the component that generated the event,
For each component, register one or more classes called listeners, which contain event handlers that are used to receive and handle this event.
The listener is the class that implements the listener interface. An event is an object that is reported only to registered listeners. Each event has a corresponding listener interface.
When you click with the mouse on the button object, a ActionEvent event is sent. This ActionEvent event is received by all ActionListener actionperformed () methods that are registered using the addActionListener () method.
The characteristics of agent-based event processing model
① events are not handled 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 an adapter (adapter) class to categorize event actions.
③ is advantageous in distributing work to various classes.
Focus on learning this event-handling model
3. Events
The three elements of event handling.
(1) The event source event source is the creator of an event, such as a button, a window, a text field, and so on.
(2) Event type Java All events are encapsulated into a class that is concentrated in the java.awt.event package, and all event classes inherit the AWTEvent class and a Method--getsouce () method that returns the object where the event occurred.
(3) The event listener receives the event and invokes the appropriate event-handling method after different types of event listeners have occurred. All event listeners are actually interfaces in a java.awt.event package, introducing the Java.util.EventListener interface. Listeners of different event types have different methods.
Event handling steps
① program Join Java.awt.event Package:
Import java.awt.event;
② registers the event listener with the required event source object:
The event source object. Addxxxlistener (Xxxlistener);
③ implement the appropriate method. If a listener interface contains more than one method, you need to implement all the methods
Example: B2.addactionlistener (This)
4, Event adapters (adapter)
The workload for all methods of implementing each listener interface is very large, and for convenience the Java language provides a adapters class for implementing classes that contain multiple methods.
The listener you define can inherit the adapter class and simply rewrite the method you need.
For example, the Listener for the window event is WindowListener, and it must implement several methods, including windowopened (), windowclosed (), windowclosing (), windowiconfied (), Windowdeiconfied (), windowactivated (), windowdeactivated (), which increases the amount of unnecessary programming effort.
If you inherit windowadapter, you just need to implement one or more of these methods, and you don't have to implement all the methods. Many of the following examples implement only one method of windowclosing () to exit the system when the window is closed.
Handling of 4.1 button events
Click the button to take the event as an action event
The event class corresponding to an action event is the ActionEvent class
The event listener for the action event is: ActionListener
Main methods of the listener:
actionperformed (ActionEvent e) is invoked when an action event occurs
Operational engineering to achieve action events:
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 the mouse event is usually a container that has mouse events when the mouse enters, leaves the container, or clicks the mouse in the container, drags the mouse, and so on.
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 () Get the location of the mouse
Mouse events correspond to two event listeners: MouseListener (or Mouseadapter) corresponds to the mouse event, Mousemotionlistener (or mousemotionadapter) corresponds to the mouse movement event.
The Main method of MouseListener (or Mouseadapter)
mousepressed (MouseEvent e) How to handle mouse down
mousereleased (mouseevent e) Mouse Release processing method
Mouseentered (mouseevent e) approach to mouse entry
mouseexited (MouseEvent e) How to handle the mouse when left
mouseclicked (MouseEvent e) How to handle mouse clicks

The Main method of Mousemotionlistener (or Mousemotionadapter)
Mousemoved (MouseEvent e) The way to handle mouse movement
Mousedraged (MouseEvent e) How to handle mouse drag
4.3 handling of keyboard events
Keyboard events occur when you press or release a keyboard in a component that has keyboard focus
The event class corresponding to the keyboard event is the KeyEvent class
The main methods of KeyEvent class:
getKeyCode () Gets the key code pressed or released
Getkeytext () Gets the string of keys pressed or released
The event listener for the keyboard event corresponds to: KeyListener or Keyadapter
Main methods:
keypressed (KeyEvent e) How to handle the keyboard when pressed
keyreleased (KeyEvent e) How to dispose of keyboard
4.4 Handling of window events
Windows and their extended classes (Frame, Dialog) can fire window events, indicating that the window is in an active/invalid state, Icon/non icon State, or on/off status, etc.
The corresponding class for the window event is windowevent, and the listener is WindowListener (or windowadapter)
Main methods:
WindowOpened (windowevent e) event handling for open windows
WindowClosed (windowevent e) event handling for closing windows
Windowclosing (windowevent e) event handling that is closing the window
WindowActivated (windowevent e) event handling for activation state
windowdeactivated (windowevent e) event handling for invalid state
4.5 handling of other events
4.5.1 check box, radio buttons event handling
The event class is itemevent:
The event listener for the option event is: ItemListener
Method:
Itemstatechanged (ItemEvent e) is invoked when an option event occurs
4.5.2 scroll bar event handling
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 invoked when an adjustment event occurs
Event handling for 4.5.3 dropdown list
The event class is itemevent:
The event listener for the option event is: ItemListener
Method:
Itemstatechanged (ItemEvent e) The Drop-down list is invoked when an action occurs
(Visible, the event handling of the Drop-down list is the same as the event type, event listener, and method and the check box, event type of the Radio box, event Listener, and method)
Handling of 4.5.4 Menu events
Menu events are usually events that occur when we click on a menu item.
There are two types of menu items:
MenuItem Action Events
Checkboxmenuitem, option Event
Event handling for MenuItem
The first step is to register the Action event Listener addActionListener (ActionListener) for all MenuItem menu items.
The second step is to implement the ActionListener interface method: actionperformed (ActionEvent e). In this method, E.getsource () is used to get the menu item selected by the user and processed accordingly.
Event handling for Checkboxmenuitem
The first step is to register the option event listener Additemlistener (ItemListener) for all checkmenuitem menu items.
The second step is to implement the ItemListener interface method: Itemstatechanged (ItemEvent e). In this method, E.getsource () Gets the menu item selected by the user, E.getitem () Gets the label of the menu item selected by the user, E.getstatechange () Gets the check, and handles it accordingly.

Ii. Exception Handling
Any good programming language and programmers will not ignore the handling of exception, as a popular object-oriented programming language--java, exception handling mechanism is also one of its important features.
General interpretation of the exception, it is said to be: programming errors. However, in fact, this error is very frequent, there are many, such as: Compile errors, running errors (specifically divided into: System run errors and logic run errors, this system runs wrong, they rarely count it as a programming error, before. )
In Java, an exception is a class that inherits from the Throwable class. Each exception class represents a Run-time error (note: It is a run error). The exception class contains information about the Run-time error and how to handle the error.
Java exception handling mechanism:
Whenever a recognized Run-time error occurs during a Java program's operation (that is, the error has an exception class that corresponds to the time it takes), the system produces an object of that exception class (note: it is called to produce an exception class object.) ) generates an exception.
Once an exception object is generated, the system must have a corresponding mechanism to deal with it, to ensure that there will be no panic, dead cycle or other damage to the operating system, thus ensuring the security of the entire program operation
Exceptions and Exception classes:
Error: Generated by Java Virtual machine and thrown, Java program does not do processing.
Runtime Exception (by 0 except system error, array subscript super Range): By system detection, user's Java program can not do processing, the system will give them to the default exception handler (Note: Default exception handling).
Exception (problem in program, predictable): Java compiler requires Java program to capture or declare all non run-time exceptions
User-generated exceptions themselves
Exception class
constructor function:
public Exception ();
Public Exception (string s); You can accept the information passed in by a string parameter, which is usually a description of the error that corresponds to the exception.
The exception class inherits several methods from Father Throwable, which are commonly used:
1) Public String toString ();
The ToString () method returns a string that describes the current exception class information.
2) public void Printstacktrace ();
The Printstacktrace () method does not return a value, its function is to complete a print operation, the current standard output (usually the screen) to print out the current exception of the stack use trajectory, that is, the program successively called which objects or classes executed which methods, The exception object is generated during the run.
system-defined run exceptions
Some of these subclasses are system-defined and included in the Java class Library, known as system-defined run-time exceptions.
user-defined exceptions
For an application-specific run-time error, programmers need to create user-defined exception classes and exception objects themselves in the user program based on the special logic of the program
User-defined exceptions typically take exception as the parent class of the exception class
But here's a question that's not yet understood: How does the system know it's recognizable when an error occurs? How to produce corresponding anomaly class object? How does an exception class object know to use the corresponding method to solve? Is there only one exception handler for each exception class object that handles the corresponding exception? ———————————— Originally, the user-defined exception was thrown by the statement throw.
When creating user-defined exceptions, you typically need to do the following:
1 Declare a new exception class so that it is a parent class or a exception class or another existing system exception class or user exception.
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 wrong information for the class.
Exception throw
If a Java program raises an identifiable error at run time, it produces an object of the exception class corresponding to the error, which is called an exception throw,
is actually thrown by an instance of the corresponding exception class object.
Depending on the exception class, the way the exception is thrown is automatically thrown by the system and the user throws two kinds:
1, the system automatically throws
System-defined run error exceptions used are automatically thrown by the system
2, the user throws
User-defined exceptions cannot be automatically thrown by the system, but must be thrown by the user in a Java statement, where the throw statement is used to explicitly throw an "exception"
Format thrown with the throw statement
Returns the Type method name (argument list) throws the list of exception class names to throw {
...
Throw exception class instance;/Note here
...
}
Attention:
1) Generally when the program satisfies a condition to throw an exception;
The throw statement is often placed in the if branch of the IF statement,
if (i>100)
Throw (new MyException ());
2 A method containing a throw statement, add the following part to the definition of the method header:
Throws list of exception class names to throw
This is done primarily to inform the upper method of calling this method, ready to accept and handle the exceptions it might throw in the runtime
If there are more than one throw statement in the method, you should list all possible exceptions 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 classes or their subclasses. If you try to throw a Throwable object, the Java compiler will complain
Exception handling:
The main considerations are how to catch exceptions, how programs jump after an exception, and how to write exception handling statements.
1. Try...catch...finally Block
1) Try
A piece of program code that might throw one or more exceptions is included in {} of the Try statement
The code actually specifies the range of exceptions that the catch block behind it can catch.
When a Java program runs to a statement in a try block, if an exception is generated, the other statements in the try block are no longer executed, and instead you go directly to the catch block to find the first matching exception type and handle it.
2) Catch block
The parameters of a 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 indicates the type of exception handled by the catch statement;
An exception object is a method code that contains the processing of an exception object in braces that the Java runtime system throws in the program code block that is specified by the try.
A catch statement can have multiple, handle different types of exceptions separately.
The Java Runtime system detects the exception types handled by each catch statement from top to bottom until it finds a matching catch statement.
Here, type matching means that the exception type in the catch is exactly the same as the type of the generated exception object or is the parent class of the exception object, so the sort order of the catch statement should be from special to general. (Consider why?) )
3) Finally block
A finally statement can be said to be a cleanup mechanism for exception handling events that is typically used to close a file or free other system resources
There can be no finally-part statement in the try-catch-finally statement.
If there is no finally part, the other program code is not executed when the program code specified by the try throws an exception;
If there is a finally part, the statement of the finally part is executed regardless of whether an exception occurred in the try block or if the statement of the catch part was executed.
Thus, the last-part statement provides a unified exit for exception handling.
Multiple exception handling
A try block may produce many different exceptions, and a multiple exception handling mechanism is required if you wish to take different approaches to handling these exceptions.
Multiple exception handling is achieved by defining several catch blocks after a try block, which is used to receive and process a particular exception object
The parameters of the catch block are used to determine whether an exception object should be an exception that is received and handled by this catch block.
By which catch block, according to the exception parameters of the exception object and the catch block: when they meet any of the following three conditions, the exception object and parameters are considered to match:
1 The exception object and the parameter belong to the same exception class.
2 The exception object belongs to the subclass of the parameter exception class.
3 The Exception object implements the interface defined by the parameter.
If the exception object produced by the try block is received by the first catch block, the process of the program jumps directly into the catch statement block and the statement block exits the current method, and the statements that have not been executed in the try block and other catch blocks are ignored
If the exception object produced by the try block does not match the first catch block, the system will automatically go to the second catch block to match, and if the second still does not match, turn to the third, fourth ... Until you find a catch block that can receive the exception object, complete the process jump.
If the exception object produced by the try block is received by the first catch block, the process of the program jumps directly into the catch statement block and the statement block exits the current method, and the statements that have not been executed in the try block and other catch blocks are ignored
If the exception object produced by the try block does not match the first catch block, the system will automatically go to the second catch block to match, and if the second still does not match, turn to the third, fourth ... Until you find a catch block that can receive the exception object, complete the process jump.
If execution of all statements in a try block does not throw an exception, all catch blocks are ignored and not executed.
Attention:
1 The statements in the catch block should perform different operations depending on the exception
Therefore, in dealing with many exceptions should pay attention to carefully design the order of the catch blocks. Catch blocks that generally handle more specific and more common exceptions should be placed ahead, while catch blocks that match a variety of exceptions should be placed in a later position.

/* Try the user to run the wrong exception handling: The problem is this, when the user input of the initial value of less than 800 is wrong, of course, if the salary changes more than 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 employee name and Payroll initial value:"); 
 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 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 ("Please enter employee name salary and create it first"); 
    } 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;//see if there's a 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,newS  
  Al-getempsalary ())); 
   else{m_empsalary=newsal; 
  return true; 
  The public string toString () {string S; 
  s= "Name:" +m_empname+ "wages:" +m_empsalary; 
 return s; } class Illegalsalaryexception extends exception{private Employee m_concernedemp; 
 
 Private double m_illegalsalary; 
  Illegalsalaryexception (Employee emp,double isal) {super ("wages lower than minimum wage"); 
  M_concernedemp=emp; 
 M_illegalsalary=isal; 
  public string toString () {string S; 
  S= "wages provided to employees are not lawful: employees:" +m_concernedemp.getempname () + "illegal Wages:" +m_illegalsalary+ "below the minimum wage amount of 800 yuan"; 
 return s; 
 } class Illegalsalarychangeexception extends exception{private Employee m_concernedemp; 
 
 Private double m_illegalsalarychange; 
  Illegalsalarychangeexception (Employee emp,double csal) {super ("Too much wage change"); 
  M_concernedemp=emp; 
 M_illegalsalarychange=csal; 
  public string toString () {string S; 
  s= "Wage changes for employees are not lawful: employees:" +m_concernedemp.getempname () + "illegal changes in wage changes:" +m_illegalsalarychange+ "higher than the original wage of 20%"; 
 return s;  } 
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.