Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

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

import java.awt.KeyboardFocusManager;

import java.awt.Window;

public class Main {
    public static Component getNearestFocusableComponent(Component c) {
        return getNearestFocusableComponent(c, null);
    }

    public static Component getNearestFocusableComponent(Component c, Container desiredRoot) {
        if (c == null)
            c = desiredRoot;
        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;
    }

    public static Window getActiveWindow() {
        KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        return mgr.getActiveWindow();
    }
}