如何在JPanel中监听关闭 [英] How to listen for close in a JPanel

查看:627
本文介绍了如何在JPanel中监听关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些奇怪的旧代码.他们有一个实现JPanel的自定义对象.此JPanel对象是主应用程序中的辅助弹出屏幕.我遇到的问题是检测辅助弹出屏幕何时关闭.

I am working with some strange legacy code. They have a custom object which implements a JPanel. This JPanel object is a secondary popup screen within the main application. The issue I'm having is to detect when the secondary popup screen is closed.

我试图为该类实现一个WindowListener,但是当我尝试添加它时,没有与该对象关联的JFrame.我认为这是因为他们使用的是自定义对象,并且它是嵌入式弹出屏幕.

I tried to implement a WindowListener for the class, but when I try to add it, there is no JFrame associated with this object. I am assuming this is because they are using a custom object and it is an embedded popup screen.

我尝试使用以下方法检索JFrame:

I tried to retrieve a JFrame using:

JFrame parentFrame = (JFrame) SwingUtilities.getWindowAncestor(this);

NullPointerException上失败.我不知道为什么很难在此页面上检测到右上角的"x"关闭按钮!我应该提到,他们能够将Mouse和Key Listeners添加到JPanel中嵌入的表中.但是整个窗口的外部监听器给我带来了麻烦.

which fails on a NullPointerException. I have no idea why it's so difficult to detect the right hand corner "x" close button on this page! I should mention that they were able to add Mouse and Key Listeners to the table which is embedded within the JPanel. But the outside listener for the entire window is causing me troubles.

(请耐心等待,这是我的第一个stackoverflow帖子,我是Swing的新手.)

(Please bear with me, this is my first stackoverflow post and I am new to Swing.)

非常感谢!

推荐答案

尝试调用

Try to call getParent() for that strange panel. It should return the parent GUI component. If this is still not your frame but some intermediate panel instead, call getParent() on it as well. The top level component returns null.

   Component p = strangePanel;
   while ( p != null && ! (p instanceof Window))
     p = p.getParent();

   ((Window) p ).addWindowListener(..);

这篇关于如何在JPanel中监听关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆