Event Handling

Download Report

Transcript Event Handling



It is necessary to import java.awt.event
package to handle events.
Every event handler requires 3 bits of
code:
1. In the class signature you need code that
specifies that the class either implements a
listener interface or extends a class that
implements a listener interface.
2. Code that tells the Event Handler class what
components to listen out for.
3. Code that implements the methods in the
listener interface.




For buttons we associate them with
ActionListener.
ActionListener are probably the most
common event handlers to implement. When
a user clicks a button an action event occurs.
Java syntax:
public class EventExample extends JFrame
implements ActionListener


As part of the class signature, we specify
that we are implementing the ActionListener
interface by using the implements keyword.
The interface defines the methods and
variables that we MUST include as part of
our code to handle action events. Omission
of these methods or variables defined in the
interface will result in a compilation error.


Next we must register an instance of this
class as a listener on a component class (e.g.
button) event source, by invoking the
addActionListener() method of the
component class (e.g. JButton class).
Syntax
◦ loginBtn.addActionListener(this);



Once we are listening for an event we must be able
to invoke a method when the event being listened
for is triggered.
The method invoked is the
actionPerformed(ActionEvent e) method.
The ActionEvent class defines one very useful
method: getSource()- this method returns a
reference to the component (object) that triggered
the event. Therefore within out actionPerformed()
method we can use if statements to determine
which components triggered the action event and
execute code in response to that action.