views:

188

answers:

2

Hello,

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!

A: 

can't you just use getParent() to obtain a reference to the outer JFrame?

Jack
Unfortunately, that doesn't seem to work :)
Jeroen from Belgium
It works when I put a (this) reference in the constructor of the JPanel when making an object of it on the JFrame class.
Jeroen from Belgium
A: 

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