Example usage for java.awt Component getFocusCycleRootAncestor

List of usage examples for java.awt Component getFocusCycleRootAncestor

Introduction

In this page you can find the example usage for java.awt Component getFocusCycleRootAncestor.

Prototype

public Container getFocusCycleRootAncestor() 

Source Link

Document

Returns the Container which is the focus cycle root of this Component's focus traversal cycle.

Usage

From source file:Main.java

public static Component findPrevFocus() {
    Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
    Container root = c.getFocusCycleRootAncestor();

    FocusTraversalPolicy policy = root.getFocusTraversalPolicy();
    Component prevFocus = policy.getComponentBefore(root, c);
    if (prevFocus == null) {
        prevFocus = policy.getDefaultComponent(root);
    }/*from   w w  w .  j a  va  2 s  .c  o m*/
    return prevFocus;
}

From source file:Main.java

public static Component findNextFocus() {
    Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
    Container root = c.getFocusCycleRootAncestor();

    FocusTraversalPolicy policy = root.getFocusTraversalPolicy();
    Component nextFocus = policy.getComponentAfter(root, c);
    if (nextFocus == null) {
        nextFocus = policy.getDefaultComponent(root);
    }//from w  ww . j a  v  a 2s.  co  m
    return nextFocus;
}

From source file:Main.java

public static Component getNearestFocusableComponent(Component c, Container desiredRoot) {
    if (c == null)
        c = desiredRoot;/*from  w  w w.  ja v  a 2 s  .  co  m*/
    if (c == null)
        c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();

    boolean cachedFocusCycleRoot = false;
    // make the desiredRoot into a focusCycleRoot
    if (desiredRoot != null) {
        cachedFocusCycleRoot = desiredRoot.isFocusCycleRoot();
        if (!cachedFocusCycleRoot)
            desiredRoot.setFocusCycleRoot(true);
    }

    Container focusRoot = null;
    if (c instanceof Container) {
        Container cnt = (Container) c;
        focusRoot = cnt.isFocusCycleRoot(cnt) ? cnt : cnt.getFocusCycleRootAncestor();
    } else
        focusRoot = c.getFocusCycleRootAncestor();

    Component focuser = null;
    if (focusRoot != null)
        //zw, remarked - selected component should become focused
        //focuser = focusRoot.getFocusTraversalPolicy().getLastComponent(focusRoot);
        focuser = c; //zw, added - selected component should become focused

    // restore the desiredRoot to its previous state
    if (desiredRoot != null && !cachedFocusCycleRoot) {
        desiredRoot.setFocusCycleRoot(cachedFocusCycleRoot);
    }
    return focuser;
}