Click to See Complete Forum and Search --> : How to close a JFrame?
Stamil
August 21st, 2000, 07:46 AM
Hello,
my class is subclassed from JPanel and I set it to the ContentPane from a JFrame.
On my panel is a close button, that should close the (parent) JFrame when pressed.
I don't know how I get this work.
Bye
mbauer
August 21st, 2000, 08:03 AM
Ok, this can be approached several ways. First off, you can add a WindowListener (or WindowAdapter) to your JFrame, and then call the dispatchEvent() method of JFrame, passing in a new WindowEvent class constructed to set the ID to WINDOW_CLOSING (Check the API guild for how to accomplish this...). This is probably the cleanest way to do this, since your WindowListener will always call the same routine to exit the program, and you can use this from menus, buttons, or whatever else you want to exit from. Here is an example:
/* This is from the application piece */
JFrame myframe = new JFrame("My Frame");
myframe.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Runtime.getRuntime().exit(0);
}
});
/* This is from the action event of the button */
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myframe.dispatchEvent(new WindowEvent(close,WINDOW_CLOSING);
}
});
Notice the code uses anonymous inner classes for both of the listeners. You don't have to use them, it just made the example code much smaller.
The other way is to cheat and use the hide() method. This doesn't really exit the window, but effectively makes it disapear. I personally would stick to the first method.
Hope this helps you out.
Mike Bauer
Michael Bauer
Stamil
August 21st, 2000, 08:50 AM
Hello Michael,
thanks a lot for your answer. But how can I get the JFrame object from my JPanel?
My code looks similar as follows:
class MyPanel extends JPanel {
...
}
class Main extends JApplet {
...
JFrame f = new JFrame("Test");
MyPanel aPanel = new MyPanel();
f.setContentPane(aPanel);
}
How can I get a refernce to JFrame f from MyPanel aPanel?
Bye
mbauer
August 21st, 2000, 11:22 AM
Ok, there is a couple of ways to do this as well. Usually what I do is I separate my application from the GUI, and all my GUI classes have get and set methods to get the components and set thier values...this is not always the best approach.
The other approach is to use the following code:
Component comp = this.getParent();
while(!comp.getClass().equals("JFrame")) {
comp=comp.getParent();
}
This should work it's way up the components and get the one you want. Once that is done, you will need to cast it to a JFrame to be able to use any of the methods.
Mike Bauer
Michael Bauer
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.