Java Reference
In-Depth Information
Figure 2-10.
Default focus ordering
Moving the Focus
As an example of some basic capabilities, let's look at how to create two listeners to handle
input focus: a
MouseListener
that moves the input focus to a component when the mouse
enters its space, and an
ActionListener
that transfers the input focus to the next component.
The
MouseListener
merely needs to call
requestFocusInWindow()
when the mouse enters
the component.
import java.awt.*;
import java.awt.event.*;
public class MouseEnterFocusMover extends MouseAdapter {
public void mouseEntered(MouseEvent mouseEvent) {
Component component = mouseEvent.getComponent();
if (!component.hasFocus()) {
component.requestFocusInWindow();
}
}
}
For the
ActionListener
, you need to call the
focusNextComponent()
method for the
KeyboardFocusManager
.
import java.awt.*;
import java.awt.event.*;