简体   繁体   English

从JPanel附加到Window事件

[英]Attach to Window events from JPanel

I'm trying to listen for a window close event on the parent JFrame of a JPanel. 我正在尝试在JPanel的父JFrame上侦听窗口关闭事件。 In the WindowClosing event I'd like to de-register a listener to a different component. 在WindowClosing事件中,我想将一个监听器取消注册到另一个组件。
Unfortunately the only code I can gaurantee to have run is the constructor for the panel. 不幸的是,我可以保证运行的唯一代码是面板的构造函数。 What this means is that the panel itself doesn't have an ancestor window yet, so simply calling SwingUtilities.getWindowAncestor doesn't work. 这意味着面板本身还没有祖先窗口,所以简单地调用SwingUtilities.getWindowAncestor是行不通的。 So what I do is register a hierarchy listener, and in the hierarchyChanged event look for SHOWING_CHANGED event. 所以我所做的是注册层次结构监听器,并在hierarchyChanged事件中查找SHOWING_CHANGED事件。 When that even fires, now I can look for the window ancestor of the panel. 当它甚至开火时,现在我可以寻找面板的窗口祖先。

So basically I have the following: 所以基本上我有以下几点:

class ShapeControlPanel extends JPanel{
    public ShapeControlPanel(){
        final ShapeControlPanel me = this;
        me.addHierarchyListener(new HierarchyListener() {
            @Override
            public void hierarchyChanged(HierarchyEvent e) {
                if((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) == HierarchyEvent.SHOWING_CHANGED){
                    SwingUtilities.getWindowAncestor(me).addWindowListener(new WindowListener() {
                        /* Snipped some empty handlers */

                        @Override
                        public void windowClosing(WindowEvent e) {
                            /* Finally get to remove the handler. */
                            me.getApparent().removeLocationSelectionListener(me.GUID(), me);
                        }
                    });
                }
            }
        });
    }
}

Is this sane? 这样理智吗? Is there a more reasonable way of getting a handle on the frame closing event? 是否有更合理的方法来处理帧关闭事件?

It's not the ugliest thing I've seen (I wouldn't even say it's all that bad), but you have to ask yourself: why does your panel really need to know when the window is closed? 这不是我见过的最丑陋的东西(我甚至不会说它有那么糟糕),但你必须问自己:为什么你的面板真的需要知道什么时候窗户关闭? It seems to be an odd coupling that would best be removed. 它似乎是一个奇怪的耦合,最好被删除。

I don't know enough about your context and what you are truly trying to accomplish to suggest an alternative right now. 我对你的背景知之甚少,以及你现在想要提出的替代方案。 But if a panel needs to know about the container in which it resides, there is probably some bad design with harmful coupling. 但是如果一个小组需要知道它所在的容器,那么可能存在一些有害耦合的不良设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM