set Swing JComponent Focus Order - Java Swing

Java examples for Swing:JComponent

Description

set Swing JComponent Focus Order

Demo Code

/*******************************************************************************
 * Copyright (c) 2010 Costantino Cerbo./*from  w w w  .  ja v a  2s  . c om*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Costantino Cerbo - initial API and implementation
 ******************************************************************************/
//package com.java2s;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.KeyStroke;

public class Main {
    static public void setFocusOrder(JComponent... components) {
        for (int i = 0; i < components.length - 1; i++) {
            setNextFocusable(components[i], components[i + 1]);
        }
        setNextFocusable(components[components.length - 1], components[0]);
    }

    static public void setNextFocusable(JComponent component,
            final JComponent nextFocusable) {
        component.getInputMap().put(
                KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0),
                "setNextFocusable");
        component.getActionMap().put("setNextFocusable",
                new AbstractAction() {
                    public void actionPerformed(ActionEvent e) {
                        nextFocusable.requestFocusInWindow();
                    }
                });
    }
}

Related Tutorials