Java中的关闭窗口(JPanel)

Java中的关闭窗口(JPanel),java,swing,Java,Swing,我在JTabbedPane中添加了一个按钮,并在JPanel中添加了如下内容: JTabbedPane tabbedPane = new JTabbedPane(); JButton btnClose = new JButton("Close"); JComponent panel.add(btnClose); tabbedPane.addTab("Test", panel); 我想按一下按钮关上窗户。我试着这样做: btnClose.addActionListener(new ActionL

我在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

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

获取顶层窗口:

public void actionPerformed(ActionEvent e) {
  JComponent comp = (JComponent) e.getSource();
  Window win = SwingUtilities.getWindowAncestor(comp);
  win.dispose();
}
确保JFrame的默认关闭操作已设置为
JFrame。在关闭时释放(首选)或
JFrame。在关闭时退出(非首选)

如果有可能从JMenuItem调用它,那么除非您首先测试comp的父项是jpopmpMenu还是JToolBar,否则它将不起作用。如果是这样的话,那么您应该使用一个更健壮的解决方案,例如,可以在中找到,特别是以下代码:

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));
        }
    }
}
资料来源: