Use Enter key to transfer focus in Swing - Java Swing

Java examples for Swing:Key Event

Description

Use Enter key to transfer focus in Swing

Demo Code

/*/*from w w w.j av a  2s  .c  o m*/
    Strandz LGPL - an API that matches the user to the data.
    Copyright (C) 2007 Chris Murphy

    Strandz LGPL is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


    The authors can be contacted via www.strandz.org
 */
//package com.java2s;

import javax.swing.JComponent;

import javax.swing.KeyStroke;

import java.awt.KeyboardFocusManager;

import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;

public class Main {
    /**
     * The source for this is
     * http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html
     *
     * @param control
     */
    public static void addEnterKey(JComponent control) {
        Set forwardKeys = control
                .getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
        Set newForwardKeys = new HashSet(forwardKeys);
        newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
        control.setFocusTraversalKeys(
                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys);
    }
}

Related Tutorials