Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Introduction to Java Interface Event-Handling : Page 3

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.


advertisement
You need two things to respond to events properly. First, you must create an event handler, and second, you must register the events you wish to handle with that event handler.

You need to do two things to create an event handler.First, implement a Listener for the type of event you wish to process. Secondly, you must provide a public method that will receive notifications when the events occur.

For example, to handle a button click, you must implement the java.awt.event.ActionListener class and provide a public actionPerformed method. The actionPerformed method takes one parameter—a java.awt.event.ActionEvent object that contains information about the event, such as the source item that generated it.



To specify that you wish to have an event acted upon, you call the addActionListener method of an object—the button in the example program—passing as a parameter the class that is will respond to its events. For example, the code in Listing 1 passes this to the addActionListner method example, meaning that this class (Class1) handles actions performed with the Button. In Java, 'this' always refers to the current object. The code shown is equivalent to writing:

btnColor.addActionListener (class1);

You can see that Listing 1 contains all the required elements, the Button, the Listener (see the btnColor.addActionListener method call), and the actionPerformed.



Comment and Contribute

 

 

 

 

 


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

 

 

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