PDA

View Full Version : EventHandler


Animal_Instinct
06-20-2007, 01:49 PM
Hi,

can anybody explain me how Event Handlers works in Java or link me any tutorial?

Tnx

ess
06-20-2007, 03:32 PM
Events in java are implemented via interfaces and/or inner class and interfaces. For example, if you have a button and you wish to add an onclick event handler for that button, than you write:

JButton button = new JButton( "Example" );
button.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
JOptionPane.showMessageDialog( null, "This is an example" ) ;
} } );

In the above sample, we used an inner class to handle button clicks on the button instance of JButton. There are other events such as on focus etc...that can be implemented for JButton instances.

If you want to implement an interfaces without declaring inner classes, than your main class must implement ActionListener interface and defines an actionPerformed method.


For a good introductory tutorial on Events in Java, check out the Sun Microsystems tutorial...which provides a good hands on guide on how to implements events in java.

http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

Cheers,
Ess

javabits
06-20-2007, 03:59 PM
The other style that ess mentions would look like this, either gets the job done so it's really just a matter of preference:

public class Example implements ActionListener
{
public Example()
{
JButton button = new JButton( "Example" );
button.addActionListener( this );
}

public void actionPerformed( ActionEvent event ) {
JOptionPane.showMessageDialog( null, "This is an example" ) ;
}
}

semper fi...