在Java应用程序中获取任何/所有活动JFrame?
有没有办法在Java应用程序中列出所有当前打开/活动(我不确定这里的术语) JFrames
在屏幕上可见? 谢谢你的帮助。
Frame.getFrames()
返回所有帧的数组。
或者如@mKorbel所述, Window.getWindows()
将返回所有窗口 – 因为Frame
(& JFrame
)扩展Window
将提供所有帧,然后是一些。 有必要迭代它们以发现哪些当前可见。
我同意Stefan Reich的评论。
一个非常有用的方法是Window.getOwnedWindows()
…以及一个有用的方法,如果不是必要的话,它是TDD(测试驱动开发):在(集成)测试中,你可以在其中显示各种Window
对象( JDialog
等),如果在测试正常结束之前出现问题(或者即使它正常完成),你通常会想要在测试的清理代码中处理从属窗口。 像这样的东西(在JUnit中):
@After public void executedAfterEach() throws Exception { // dispose of dependent Windows... EventQueue.invokeAndWait( new Runnable(){ @Override public void run() { if( app.mainFrame != null ){ for( Window window : app.mainFrame.getOwnedWindows() ){ if( window.isVisible() ){ System.out.println( String.format( "# disposing of %s", window.getClass() )); window.dispose(); } } } } }); }
Frame.getFrames()
将完成你的工作。
来自oracle Doc:
返回此应用程序创建的所有Frame的数组。 如果从applet调用,则该数组仅包含该applet可访问的Frame。
一个简单的例子:
//all frames to a array Frame[] allFrames = Frame.getFrames(); //Iterate through the allFrames array for(Frame fr : allFrames){ //uncomment the below line to see frames names and properties/atr. //System.out.println(fr); //to get specific frame name String specificFrameName = fr.getClass().getName(); //if found frame that I want I can close or any you want //GUIS.CheckForCustomer is my specific frame name that I want to close. if(specificFrameName.equals("GUIS.CheckForCustomer")){ //close the frame fr.dispose(); } }
您也可以像其他人一样使用Window.getWindows()
。