Home
01 Getting Started
02 Concepts
03 Variables & Data Types
04 Control Logic
05 Modifiers
06 GUI
07 Other Useful Classes
08 Handling Events
a List of Listeners
b Prepare to Listen
c Action Listener
d Item Listener
09 Handling Exceptions
10 Project 01 - Mortg Calc
11 More on Applets
12 Layout Manager
13 Project 02 - Calculator
14 Threads
15 Project 03 - Wake Up
16 File I/O
17 Project 04 - File I/O
Expanded Table of Contents
Debugging Hints
HTML Review
Download Samples
|
Previous Next
Set Up the Event Listener
To get our objects to respond to us, we will have to do the following:
- Import the package that contains the event listener interfaces.
import java.awt.event.*;
- Have the class implement the event listener interface. The class will have to override all the methods contained in the interface. For example:
public class CheckAction extends JFrame implements ActionListener {
- Create the objects and add the event listener to them. The "this" refers to the class in which this code is found and that implements the listener.
JButton btn = new JButton("Push Me ");
JCheckBox chk = new JCheckBox("Do you want a refund?");
btn.addActionListener(this);
chk.addActionListener(this);
- Override the method that must respond to the event. If more than one object can cause this event, test to see which is the source of this occurrence.
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == btn) {
process button
} else if (source == chk) {
process check box
}
}
Previous Next
|
|