Java Reference
In-Depth Information
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.
Focus applies to all components that can receive input. In a JButton object, a dotted out-
line appears on the button that has the focus.
A component can be given the focus by calling its requestFocus() method with no
arguments, as in this example:
JButton ok = new JButton(“OK”);
ok.requestFocus();
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) {
// ...
}
To determine which object gained or lost the focus, the getSource() method can be
called on the FocusEvent object sent as an argument to the focusGained() and
focusLost() methods.
Listing 12.2 contains a Java application that displays the sum of two numbers. Focus
events are used to determine when the sum needs to be recalculated.
LISTING 12.2
The Full Text of Calculator.java
1: import java.awt.event.*;
2: import javax.swing.*;
3: import java.awt.*;
4:
5: public class Calculator extends JFrame implements FocusListener {
6: JTextField value1 = new JTextField(“0”, 5);
7: JLabel plus = new JLabel(“+”);
8: JTextField value2 = new JTextField(“0”, 5);
9: JLabel equals = new JLabel(“=”);
Search WWH ::




Custom Search