Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the Java events and error handling methods

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the Java event and error handling method". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what the Java event and error handling method is.

12.1 event handling

Impart new knowledge

Message-driven and event handling are the main features of object-oriented programming technology. as soon as it changes the order of process language execution, the whole program takes the program code as the main line, but becomes the idea that the user and the user of the program is the main line.

Generally speaking, in the previous programming idea, the running process of the whole program is mainly based on the program itself, and the whole running process is predefined in the program. In the idea of object-oriented programming, the user is allowed to take the initiative, and the whole running process is determined by the user. Once the application has finished building the GUI, it no longer works, but waits for the user to notify it through the mouse and keyboard (message-driven), and then handles it accordingly (event handling) according to the content of the notification.

Let's recall that when we explained the use of buttons, we used such a program in the program:

Button1.addActionListener (new ActionListener ()

{

Public void actionPerformed (ActionEvent evt)

{

Toolkit.getDefaultToolkit () .beep ()

}

});

At that time, we had already described its function: first, an event monitor was added to the button buuton1, which was used to monitor whether the button was pressed (ActionEvent). In addition, we have written a segment of event handling:

Public void actionPerformed (ActionEvent evt)

{

Toolkit.getDefaultToolkit () .beep ()

}

When the button is pressed, the program segment is executed, and the Toolkit.getDefault.Toolkit (). Beep () method is executed, that is, a bell is rung.

When you write an "event handling" segment in a program, you can usually do it in the following steps:

1. Determine the event type

Almost every action a user does with a mouse or keyboard will cause a message, that is, an event, but we don't have to react to all of these events, some of which are not our concern. For different parts, the events we need to care about are often different. Some of the most commonly used events are listed in the following table.

Assembly event type event description

JButton ActionEvent pressed the button.

CheckBox ActionEvent Select or deselect the check box

JTextField ActionEvent user input text enter enter key

Table 12-1 Common parts-event list

two。 Add a monitor for the event to the widget

Each event type has a corresponding interface, usually called XXXListener, where XXX represents the type of event it handles. These interfaces are included in the java.awt.event and javax.swing.event packages. For example:

Button1.addActionListener (new ActionListener ()

{

……

});

3. Add event handlers

Finally, we have to add flesh and blood to it, the actual event handler.

As you can see, writing event handlers is not an easy task, let alone writing good event handlers. Since this book is an introduction to Java, it does not list all the events of each part and explain them one by one. Here, I only ask you to have a rough understanding of the event handling process through learning, so that you can learn and study all kinds of knowledge related to event handling.

Example illustration

We used Frame to build applets in Chapter 10, when we could see a new pop-up window, a Frame, with maximize, minimize, and close buttons. I wonder if readers have noticed that in this Frame, the close button does not take effect because the handling of this event is not defined in the program. Let's take a look at a program and see how it makes this close button work. By convention, we first create a source program:

Source program: closeTest.java

Import javax.swing.*

Import java.awt.*

Import java.awt.event.*

Public class closeTest

{

Public static void main (String args [])

{

Frame frame1=new Frame ("This is a Frame")

Frame1.addWindowListener (new WindowAdapter ()

{

Public void windowClosing (WindowEvent e)

{

System.exit (0)

}

});

Frame1.setSize (200200)

Frame1.show ()

}

}

This is an Java application, we first compile using javac, and then execute:

Java closeTest

To execute this program, the output of the program is extremely simple:

Figure 12-1 output of program closeTest.java

Some tips:

This program also shows from the side that we can also use the GUI interface in Java applications, although we always use the Java applet (Applet) as an example.

The output of the program is a blank Frame. Press the close button now, and you will find that the Frame is immediately closed. We achieved our goal.

Impart new knowledge

Next, let's take a look at this program:

1)

Public static void main (String args [])

You should remember that a Java application (Application) starts with the main method!

2)

Frame frame1=new Frame ("This is a Frame")

At this point, we have defined a Frame, which we have learned and will not say much about.

3)

Frame1.addWindowListener (new WindowAdapter ()

{

Public void windowClosing (WindowEvent e)

{

System.exit (0)

}

});

This procedure is the most important part of this section. It adds an event monitor about window (window) to the container frame1. What are the events being monitored? It's windowClosing, which means pressing the close button.

If the button is detected to be pressed, the System.exit (0) exit program is executed.

4)

Frame1.setSize (200200)

Frame1.show ()

We should be familiar with these two sentences. We first set the Frame to 20000200, and then call the show method to display it.

Self-test exercise

1) what happens when an event occurs in a widget but no event monitor is specified for the event in the widget? ________________.

a. When compiled, it will not pass b. Causing a fatal error in the Java program

c. Ignore this event d. Raise default event handling

2) usually we use the _ method to add an event monitor to a widget.

A.addXXXListener b.XXXListener

3) the event monitor is included in the _ package.

A.java.awt.happen b.java.until c.java.awt.event

4) the button presses the event name is _.

A.PressedEvent b.ActionEvent

5) JButton objects cannot be used in Java applications (Application)? _______.

a. To b. Wrong

6) only GUI parts can generate events? ___________.

a. To b. Wrong

Please state the reasons:

_

Practice the answer

1) C this event will be ignored because there is no default event handling in Java. Of course, it will not make Java program abnormal exit, Java is not so fragile!

2) a when you encounter a statement in this form, you add an event monitor.

3) c in java.awt.event and javax.swing.event.

4) b ActionEven.

5) b although we have been using Applet as an example, this does not prove that these GUI parts cannot be used in Application. We can use this GUI widget to form an Application program.

6) b this is an illusion, the simplest example is Frame, it is a container, in fact, there are many things can happen.

12.2 error handling

Impart new knowledge

"there is no such thing as a completely error-free program." We do not discuss whether it is a truth or not. But it is indeed a warning that we must be careful to avoid mistakes as much as possible when writing programs.

When the program goes wrong, it will be beyond the programmer's control, making the program "poles apart", not only can not complete the function normally, but also some terrible things will occur.

Note:

There are countless accidents caused by errors in programming, and the greatest loss is a rocket launch in the United States. In that tragedy, the rocket exploded in the sky because of the wrong "," written ";" in the program. Therefore, it is necessary to spend a lot of manpower and material resources to prevent programming errors.

The most effective solution is to consciously add mechanisms to program design so that it can detect itself at run time and report errors before they get out of control.

One of the most common error handling is to return a status value for each method (in other languages, that is, each function) to indicate whether the method completed the task successfully and correctly. When the program that calls this method receives an error status value, you can know that the program is wrong, and then take effective measures to avoid the problem caused by the error (the easiest way is to exit the program or give a hint to remind the operator).

Let's look at a simple example:

Public int getIndex (String emailaddr)

{

For (int xerox

This method is used to find the location of the "@" character in the emailaddr string and then return the location value. But careful readers should be able to quickly ask a question: if there is no "@" character in emailaddr, what will the program return?

Yes, this is the possibility of potential mistakes. When there is no "@" character in emailaddr, no matter what value is returned, one thing you can be sure of is that the value returned must be incorrect!

Then, the program that called this method did not know that it got an error return! It continues to run as a correct value. Oh, no, the dominoes are on! A mistake triggered.

So, at this time, we should give a hint to the program that calls this method, that is, to return an explicit error value, for example, we can use-1 to indicate that it is not found. Using this idea, we rewrite the program to form:

Public int getIndex (String emailaddr)

{

For (int xerox

We added a sentence to the original program: return (- 1), when the logic of the program has changed, and when the "@" symbol is found, it will return to its location. If it cannot be found, then: return (- 1) is executed.

Then we can realize that the error occurred when the program that called this method received a return value of-1.

Self-test exercise

1) Please create a method that looks in the integer array intArray to see if there is a member of 5, and returns its location. And please note that some error handling mechanisms are added.

What error handling mechanism do you use in this program?

_

If the value of the integer array intArray is {2, 5, 5, 6, 9, 10}, what value is returned?

_

What value will be returned if the value is {4pd6, 2pr, 90pc8}?

_

Practice the answer

1) the following is an example:

Public int searchfive (int intArray [])

{

For (int xerox

In this program, we use a general error identification mechanism, that is, find the number 5, return its location, and when the number 5 is not found, return-1. This lets the program that calls the method know the execution effect of the method.

If the value of the integer array intArray is {2, 5, 5, 6, 9, 10}, then 1 is returned.

And if the value is {4pd6pr 2je 90je 8}, then 5 will not be found, so-1 will be returned.

12.3 exception handling

Impart new knowledge

In some cases, however, there is no clear distinction between a legal return value and a return value that identifies an error situation. The place where the error occurs in this case is called an abnormal situation. This exception error is fatal and often causes the program to exit abnormally.

In the Java language, some tools are provided to deal with these exception cases, which can better deal with these situations and make Java programs more robust. As the content in this area is relatively advanced, it is difficult to use a short space to explain, so this book (an introductory book) only with a few words, to make a brief introduction to you.

1. The flow of exception handling

In Java, an exception is an object defined by the Exception class. Once an exception is generated, the normal control flow of the method stops immediately, and the Java virtual machine (JVM) will try to find a handler that can be caught and handle this particular exception. If the handler cannot be found, the Exception object is passed to the upper layer and uploaded layer by layer, up to the program's main method. If the handler is still not found, the program will exit from running.

In other words, Java has defined many exceptions in advance (using the Exception class definition). When an exception occurs in a program, the Java virtual machine will find a way to eliminate the exception (that is, find the corresponding handler). If it cannot be found in the current method, it will report the exception to the program segment that called the method, and then continue to look for the corresponding program. If you can't find it, pass it up to the program's main method. If none of them are found, the program exits abnormally.

two。 Build an exception handling program

So how do you build this exception handler? We can set this through the try/catch program structure:

Try

{

……

}

Catch (Exception ex)

{

……

}

When the code in the try block generates the exception specified in the catch block, it skips the later code in the try block and executes the program in the catch block.

If the code within the try block does not generate the exception specified in the catch block, the program within the catch block is skipped.

Thank you for your reading, the above is the content of "what are Java events and error handling methods". After the study of this article, I believe you have a deeper understanding of what Java events and error handling methods are, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report