Raj
Raj

Reputation: 69

Close Window (JPanel) in Java

I have a Button added to a JTabbedPane added to a JPanel with something like this:

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

I want to close the window on the button press. I tried do this:

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

But it gives me

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

How do I close the Window on Button Press

Upvotes: 4

Views: 8816

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Get the top level window:

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

Make sure that the JFrame's default close operation has been set to JFrame.DISPOSE_ON_CLOSE (preferred) OR JFrame.EXIT_ON_CLOSE (not preferred).

If there is ever a chance that this will be called from a JMenuItem, then it will not work unless you first test if the comp's parent is either a JPopupMenu or a JToolBar. If so, then you should use a more robust solution such as can be found at java-swing-tips, specifically this code:

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));
        }
    }
}

source: WindowClosingAction

Upvotes: 12

Related Questions