2. Swing handles events with a set of interfaces
called event listeners. You create a listener
object and associate it with the user interface
component being monitored.
Event Listeners
If a class wants to respond to a user event under the
Java event-handling system, it must implement the
interface that deals with the events. These interfaces
are called event listeners.
• Each listener handles a specific kind of event.
3. The java.awt.event package contains all the basic
event listeners, as well as the objects that represent
specific events.
• ActionListener—Action events, which are generated
by a user taking an action on a component, such as a
click on a button
• AdjustmentListener—Adjustment events, which are
generated when a component is adjusted, such as
when a scrollbar is moved
• FocusListener—Keyboard focus events, which are
generated when a component such as a text field
gains or loses the focus
4. • KeyListener—Keyboard events, which occur when a
user enters text on the keyboard
• MouseListener—Mouse events, which are generated
by mouse clicks, a mouse entering a component’s
area, and a mouse leaving a component’s area
• WindowListener—Window events, which are
generated by a window being maximized, minimized,
moved, or closed
5. A class can implement as many listeners as needed. The
following class is declared to handle both action and text
events:
public class Test extends JFrame implements ActionListener
{
// ...
}
Setting Up Components
When you make a class an event listener, you have set up
a specific type of event to be heard by that class.
6. The following example creates a JButton object and
associates an action event listener with it:
JButton ok = new JButton(“OK”);
ok.addActionListener(this);
All the listener adding methods take one
argument: the object that is listening for events
of that kind. Using “this” indicates that the
current class is the event listener. You could
specify a different object, as long as its class
implements the right listener interface.
7. Event-Handling Methods
When you associate an interface with a class, the class
must handle all the methods contained in the interface.
The ActionListener interface has only one method:
actionPerformed(). All classes that implement
ActionListener must have a method with the following
structure:
public void actionPerformed(ActionEvent event)
{
// handle event here
}
8. If only one component in your program’s graphical
user interface has a listener for action events, you will
know that this actionPerformed() method only is
called in response to an event generated by that
component.
If more than one component has an action event
listener, you must use the ActionEvent object to
figure out which component was used and act
accordingly in your program. This object can be used
to discover details about the component that
generated the event.
9. public void actionPerformed(ActionEvent event)
{
Object source = evt.getSource();
}
The object returned by the getSource() method can
be compared with components by using the ==
operator.
10. if (source == quitButton) {
quitProgram();
}
if (source == sortRecords) {
sortRecords();
}
The quitProgram() method is called if the
quitButton object generated the event, and the
sortRecords() method is called if the sortRecords
button generated the event.
11. The instanceof operator can be used in an event-
handling method to determine what class of
component generated the event.
void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source instanceof JTextField) {
calculateScore();
} else if (source instanceof JButton) {
quitProgram();
}
}
12. import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class TitleChanger extends JFrame implements ActionListener
{
JButton b1 = new JButton("ATI NAIWALA");
JButton b2 = new JButton("ATI DEHIWALA");
public TitleChanger() {
super("Title Bar");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1.addActionListener(this);
b2.addActionListener(this);
FlowLayout flow = new FlowLayout();
setLayout(flow);
add(b1);
add(b2);
pack();
setVisible(true);
}
13. public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
if (source == b1) {
setTitle("ATI NAIWALA");
} else if (source == b2) {
setTitle("ATI DEHIWALA");
}
repaint();
}
public static void main(String[] arguments) {
TitleChanger frame = new TitleChanger();
}
}
14. In addition to the getSource() method, you can use the
getActionCommand() method on the ActionEvent object
to discover more information about the event’s source.
By default, the action command is the text associated
with the component, such as the label on a button. You
also can set a different action command for a
component by calling its setActionCommand(String)
method. The string argument should be the action
command’s desired text.
15. JButton sort = new JButton(“Sort”);
JMenuItem menuSort = new JMenuItem(“Sort”);
sort.setActionCommand(“Sort Files”);
menuSort.setActionCommand(“Sort Files”);
Action commands are useful in a program in which
more than one component should cause the same
thing to happen. By giving both components the
same action command, you can handle them with
the same code in an event-handling method.
16. Focus Events
Focus events occur when any component gains or
loses input focus on a graphical user interface.
Focus describes the component that is active for
keyboard input. If one of the fields has the focus (in a
user interface with several editable text fields), a
cursor blinks in the field. Any text entered goes into
this component.
A component can be given the focus by calling its
requestFocus() method with no arguments,
JButton ok = new JButton(“OK”);
ok.requestFocus();
17. To handle a focus event, a class must implement the
FocusListener interface. Two methods are in the
interface: focusGained(FocusEvent) and
focusLost(FocusEvent).
They take the following forms:
public void focusGained(FocusEvent event) {
// ...
}
public void focusLost(FocusEvent event) {
// ...
}
18. mport java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Calculator extends JFrame implements
FocusListener {
JTextField value1 = new JTextField("0", 5);
JLabel plus = new JLabel("+");
JTextField value2 = new JTextField("0", 5);
JLabel equals = new JLabel("=");
JTextField sum = new JTextField("0", 5);
19. public Calculator() {
super("Add Two Numbers");
setSize(350, 90);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flow = new
FlowLayout(FlowLayout.CENTER);
setLayout(flow);
// add listeners
value1.addFocusListener(this);
value2.addFocusListener(this);
sum.setEditable(false);
add(value1);
add(plus);
add(value2);
add(equals);
add(sum);
setVisible(true);
}
20. public void focusGained(FocusEvent event) {
try {
float total = Float.parseFloat(value1.getText()) +
Float.parseFloat(value2.getText());
sum.setText("" + total);
} catch (NumberFormatException nfe) {
value1.setText("0");
value2.setText("0");
sum.setText("0");
}
}
public void focusLost(FocusEvent event) {
focusGained(event);
}
public static void main(String[] arguments) {
Calculator frame = new Calculator();
}
}