Java Swing Focus focusComponent(Component comp)

Here you can find the source of focusComponent(Component comp)

Description

Tries to focus the given component.

License

Apache License

Parameter

Parameter Description
comp The component to receive the focus

Return

true if an egligable component has been found
false Otherwise

Declaration

public static boolean focusComponent(Component comp) 

Method Source Code

//package com.java2s;
/*//from ww  w .  ja  v a  2s  . com
 *   Copyright 2007 skynamics AG
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

import java.awt.Component;
import java.awt.Container;

import javax.swing.JScrollPane;

public class Main {
    /**
     * Tries to focus the given component.
     * In difference to Component.requestFocus (), the method tries to find a descendant component that is focusable.
     * Note that a true result does merely indicate that a focusable component has been found,
     * not the actual passing of the focus.
     *
     * @param comp The component to receive the focus
     * @return
     *      true   if an egligable component has been found<br>
     *      false   Otherwise
     */
    public static boolean focusComponent(Component comp) {
        if (comp == null) {
            return false;
        }

        if (comp.isFocusable() && !(comp instanceof JScrollPane)) {
            comp.requestFocus();
            return true;
        }

        if (comp instanceof Container) {
            Component[] comps = ((Container) comp).getComponents();

            for (int i = 0; i < comps.length; i++) {
                if (focusComponent(comps[i])) {
                    return true;
                }
            }
        }

        return false;
    }
}

Related

  1. clearAWTFocus(Robot robot)
  2. compositeRequestFocus(Component component)
  3. containerContainsFocus(Container cont)
  4. containerContainsFocus(Container cont)
  5. createWizardFocusAdapter()
  6. focusComponentOrChild(Component c)
  7. focusComponentOrChild(Component c, boolean deepest)
  8. focusFirstFocusableChild(Container c)
  9. focusFirstFocusableComponent(Component c)