检测是否已隐藏Java

检测是否已隐藏Java

本文介绍了检测是否已隐藏Java Swing组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下Swing应用程序:

Assume we have the following Swing application:

    final JFrame frame = new JFrame();

    final JPanel outer = new JPanel();
    frame.add(outer);

    JComponent inner = new SomeSpecialComponent();
    outer.add(inner);

因此,在本例中,我们只在框架中有一个外部面板,在面板中有一个特殊组件。隐藏和显示此特殊组件时必须执行某些操作。但问题是setVisible()在外部面板上调用而不是在特殊组件上调用。所以我不能覆盖特殊组件中的setVisible方法,我也不能在其上使用组件监听器。我可以在父组件上注册监听器,但是如果外面板也在另一个面板中并且这个外部外面板是隐藏的呢?

So in this example we simply have an outer panel in the frame and a special component in the panel. This special component must do something when it is hidden and shown. But the problem is that setVisible() is called on the outer panel and not on the special component. So I can't override the setVisible method in the special component and I also can't use a component listener on it. I could register the listener on the parent component but what if the outer panel is also in another panel and this outer outer panel is hidden?

是否有一个比递归更简单的解决方案将组件侦听器添加到所有父组件以检测SomeSpecialComponent中的可见性更改?

Is there an easier solution than recursively adding component listeners to all parent components to detect a visibility change in SomeSpecialComponent?

推荐答案

要侦听此类事件中发生的事件层次结构,您可以执行以下操作。

To listen for this kind of events occuring in the hierarchy, you could do the following.

class SomeSpecialComponent extends JComponent implements HierarchyListener {

    private boolean amIVisible() {
        Container c = getParent();
        while (c != null)
            if (!c.isVisible())
                return false;
            else
                c = c.getParent();
        return true;
    }

    public void addNotify() {
        super.addNotify();
        addHierarchyListener(this);
    }

    public void removeNotify() {
        removeHierarchyListener(this);
        super.removeNotify();
    }

    public void hierarchyChanged(HierarchyEvent e) {
        System.out.println("Am I visible? " + amIVisible());
    }

}

你甚至可以更准确地说HierarchyEvents的处理。看看

You could even be more precise in the treatement of HierarchyEvents. Have a look at

这篇关于检测是否已隐藏Java Swing组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 06:00