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

解决方法

我有一个按钮添加到JTabbedPane添加到JPanel与这样的事情:

JTabbedPane tabbedPane = new JTabbedPane();
JButton btnClose = new JButton("Close");
JComponent panel.add(btnClose);
tabbedPane.addTab("Test",panel);

我想在按钮按下时关闭窗口。我尝试这样做:

btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                panel.dispatchEvent(new WindowEvent(frame,WindowEvent.WINDOW_CLOSING));
            }
        });

但这给了我

 Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: null source

我如何在按下按钮时关闭窗口

猜你在找的技术问答相关文章

如何检查配对的蓝牙设备是打印机还是扫描仪(Android)
是否允许实体正文进行HTTP DELETE请求?
如何将ZipInputStream转换为InputStream?
java.util.logging Java 8中的变量
PowerMockito.doReturn返回null
Java中的RESTful调用
Swing / Java:如何正确使用getText和setText字符串
特殊字符和重音字符
Android Studio中的ndk.dir错误
错误“找不到主类”