Introduction to Java Interface Event-Handling : Page 4
Java is an event-driven language. This means that program flow usually varies dependent upon what actions a user performs, and differs from traditional procedural-based languages where program execution was very linear. Here's what you need to know to make your Java programs respond to events such as the user moving the mouse or clicking a button.
by David M. Williams
Oct 21, 2002
Page 4 of 4
You should realize that there are three consequences of the event sequence framework.
First, the code to manage the graphical user interface (GUI) can be separated from the code to handle events and code to handle the application logic.
This simple applet has just one class which both displays the initial screen and responds to the button click. However, you could easily modify the program and split the logic into two classes. One class would contain the interface code, and the other would respond to the button clicks. Listing 3 shows how that alteration looks, and Listing 4 shows an HTML file to display the changed applet).
Note that class2 creates an instance of class3 (named clsListener). Class2 uses clsListener as the parameter to the addActionListener method. Therefore, when a user clicks on the button, Java fires the actionPerformed method in class3 to handle to the event.
You will also notice that the code contains some sleight-of-hand to achieve the separation. Class3 contains a setup method so it can reference the button in class2it needs to be able to manipulate the button in the actionPerformed method.
The name of the addActionListener method suggests subtly that you can register many different listeners for any event. So, the second consequence is that you can trigger a series of events in many different classes, all of which fire when a user clicks the button. Figure 4 shows a sequence diagram for an event that triggers multiple event-handlers.