Tries to determine the frame the container is part of. - Java Swing

Java examples for Swing:JComponent

Description

Tries to determine the frame the container is part of.

Demo Code

/*//from  ww w.  j  a  va2  s  .  co m
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program 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 General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;

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

import java.awt.Frame;

public class Main {
    /**
     * Tries to determine the frame the container is part of.
     *
     * @param cont   the container to get the frame for
     * @return      the parent frame if one exists or null if not
     */
    public static Frame getParentFrame(Container cont) {
        return (Frame) getParent(cont, Frame.class);
    }

    /**
     * Tries to determine the frame the component is part of.
     *
     * @param comp   the component to get the frame for
     * @return      the parent frame if one exists or null if not
     */
    public static Frame getParentFrame(Component comp) {
        if (comp instanceof Container)
            return (Frame) getParent((Container) comp, Frame.class);
        else
            return null;
    }

    /**
     * Tries to determine the parent this panel is part of.
     *
     * @param cont   the container to get the parent for
     * @param parentClass   the class of the parent to obtain
     * @return      the parent if one exists or null if not
     */
    public static Object getParent(Container cont, Class parentClass) {
        Container result;
        Container parent;

        result = null;

        parent = cont;
        while (parent != null) {
            if (parentClass.isInstance(parent)) {
                result = parent;
                break;
            } else {
                parent = parent.getParent();
            }
        }

        return result;
    }
}

Related Tutorials