Skip to main content

Tipsy Snipsy: Forward Focus Traversal

Posted by evanx on March 15, 2007 at 7:59 AM EDT

As you've noticed, when you press Enter on fields like JTextField et al, an ActionEvent is generated, and focus is not transferred to the next field in the focus cycle.

But what if you are not interested in ActionEvent's on fields, and would rather Enter have the same effect as Tab, maybe because your users are used to having to enter data with the Enter key?

    protected void setDefaultFocusTraversalKeys() {
        Set set = new HashSet(
                KeyboardFocusManager.getCurrentKeyboardFocusManager().
                getDefaultFocusTraversalKeys(
                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
        set.add(KeyStroke.getKeyStroke("ENTER"));
        KeyboardFocusManager.getCurrentKeyboardFocusManager().
                setDefaultFocusTraversalKeys(
                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
    }   

But then we aint gonna get those ActionEvent's no more, which may or may not be a problem.


References

Setting Focus Traversal Keys for the Entire Application on JavaAlmanac.com.

Using the Swing Focus Subsystem on the Java Tutorial.


Related Topics >>