Java Reference
In-Depth Information
Line 12: Quotient = 6.25
Sample Run 2: (In this sample run, the user input is shaded.)
Line 4: Enter the numerator: 20
Line 7: Enter the denominator: 0
Line 14: MyDivisionByZeroException: Cannot divide by zero
If the exception class you create is a direct subclass of the class Exception —or a
direct subclass of an exception class whose exceptions are checked exceptions—then the
exceptions of the class you created are checked exceptions.
Event Handling
The previous sections discussed in detail Java's mechanism of exception handling. You
learned that Java offers extensive support for handling exceptions by providing a number
of exception classes. In previous chapters, you learned that Java also provides powerful yet
easy-to-use GUI components to create programs that can visually interact with the user.
A major item that is required in creating a GUI is the handling of events. In Chapter 6,
you learned that when you click a button or press the Enter key in a text field, it
generates an action event. In fact, when you press a mouse button to click a button, in
addition to generating an action event, a mouse event is generated. Similarly, when you
press the Enter key in a text field, in addition to the action event, it generates a key
event. Therefore, a GUI program can simultaneously generate more than one event. In
the remainder of this section, you will learn how to handle other action events, such as
windows and mouse events.
As described in Chapter 6, Java provides various interface s to handle different events.
For example, to handle action events, you use the interface ActionListener and to
handle mouse events, you use the interface MouseListener . Key events are handled
by the interface KeyListener ; and window events are handled by the interface
WindowListener . These and other interfaces contain methods that are executed when a
particular event occurs. For example, when an action event occurs,
the method
actionPerformed of the interface ActionListener is executed.
To handle an event, we create an appropriate object and register it with the GUI component.
Recall that the methods of an interface are abstract . That is, they contain only the headings
of the methods. Therefore, you cannot instantiate an object of an interface. To create an
object to handle an event, first you create a class that implements an appropriate interface.
 
 
Search WWH ::




Custom Search