Java Reference
In-Depth Information
public class ActionFocusMover implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
KeyboardFocusManager manager =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.focusNextComponent();
}
}
The ActionFocusMover and MouseEnterFocusMover show two different ways of programmati-
cally moving focus around. The ActionFocusMover uses the KeyboardFocusManager for traversal.
In MouseEnterFocusMover , the call to requestFocusInWindow() says that you would like for the
suggested component to get focus for the window of the application. However, getting focus
can be turned off. If the component isn't focusable, either because the default setting of the
focusable property is false or you called component.setFocusable(false) , then the component
will be skipped over and the next component after it gets focus; the component is removed
from the tab focus cycle. (Think of a scrollbar that isn't in the focus cycle, but is draggable to
change a setting.)
The program in Listing 2-11 uses the two event handlers for moving focus around. It creates a
3×3 grid of buttons, in which each button has an attached mouse listener and a focus listener.
The even buttons are selectable but aren't focusable.
Listing 2-11. Focus Traversal Sample
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FocusSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Focus Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener actionListener = new ActionFocusMover();
MouseListener mouseListener = new MouseEnterFocusMover();
frame.setLayout(new GridLayout(3,3));
for (int i=1; i<10; i++) {
JButton button = new JButton(Integer.toString(i));
button.addActionListener(actionListener);
button.addMouseListener(mouseListener);
if ((i%2) != 0) { // odd - enabled by default
button.setFocusable(false);
}
frame.add(button);
}
Search WWH ::




Custom Search