Browse DevX
Sign up for e-mail newsletters from DevX


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.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 class2—it 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.

David M. Williams is an Australian I.T. writer, trainer and consultant. He is the author of Win32 Font Lister and other shareware programs. Reach him by e-mail at dave@qed.newcastle.edu.au.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date