1

I'm trying to dispose my JFrame by clicking a button, located on a JPanel that is placed on the JFrame that I want to close.

I tried to make a static method on the JFrame class, but ofcourse my IDE told me that wasn't going to happen.

Anyone thinking of a solution?

Thanks!

Jeroen
  • 128
  • 2
  • 14

2 Answers2

0

Try this:

public class DisposeJFrame extends JFrame{
    JPanel panel = new JPanel();
    JButton button = new JButton("Dispose JFrame");

    public DisposeJFrame(){
        super();
        setTitle("Hi");
        panel.add(button);
        add(panel);
        pack();

        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent arg0) {
                dispose();
            }
        });
    }

    public static void main(String args[]){
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                DisposeJFrame jf = new DisposeJFrame();
                    jf.setVisible(true);
            }
        });
    }
}
Cesar
  • 5,488
  • 2
  • 29
  • 36
0

Do something like this:

JButton closeFrameButton = new JButton("Close");
closeFrameButton.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        ((Window) getRootPane().getParent()).dispose();
    }
});
  • 1
    Answers with working code are nice, when they have explanations why it works they're even better. (Welcome to Stack Overflowtoo btw) – indivisible Jun 22 '14 at 06:39
  • Calling [getTopLevelAncestor](https://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#getTopLevelAncestor--) is safer than assuming the JRootPane is a direct child of the window. In fact, if the component is in a JInternalFrame, this code won't work at all. – VGR Dec 12 '15 at 18:11