栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java中的关闭窗口(JPanel)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中的关闭窗口(JPanel)

获取顶层窗口:

public void actionPerformed(ActionEvent e) {  JComponent comp = (JComponent) e.getSource();  Window win = SwingUtilities.getWindowAncestor(comp);  win.dispose();}

确保已将Jframe的默认关闭操作设置为

Jframe.DISPOSE_ON_CLOSE
(首选)或
Jframe.EXIT_ON_CLOSE
(首选)。

如果有可能会从JMenuItem调用此方法,那么除非您首先测试组件的父级是JPopupMenu还是JToolBar,否则它将不起作用。如果是这样,那么您应该使用更健壮的解决方案,例如可以在java-
swing-tips上找到
,特别是以下代码:

class ExitAction extends AbstractAction {    public ExitAction() {        super("Exit");    }    @Override public void actionPerformed(ActionEvent e) {        JComponent c = (JComponent) e.getSource();        Window window = null;        Container parent = c.getParent();        if (parent instanceof JPopupMenu) { JPopupMenu popup = (JPopupMenu) parent; JComponent invoker = (JComponent) popup.getInvoker(); window = SwingUtilities.getWindowAncestor(invoker);        } else if (parent instanceof JToolBar) { JToolBar toolbar = (JToolBar) parent; if (((BasicToolBarUI) toolbar.getUI()).isFloating()) {     window = SwingUtilities.getWindowAncestor(toolbar).getOwner(); } else {     window = SwingUtilities.getWindowAncestor(toolbar); }        } else { Component invoker = c.getParent(); window = SwingUtilities.getWindowAncestor(invoker);        }        if (window != null) { //window.dispose(); window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING));        }    }}

来源:WindowClosingAction



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/596180.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号