Reputation: 445
So I have 2 Java classes, each of which creates a JFrame with various components in it. Each class has its own addComponentsToPane(...)
method which is to set up the contents of the frame. this is used in the createAndShowGui()
method which is invoked in the main method of the class.
Let's call them class A and B. So the thing is, in A I have a button that when clicked, launches B (simple call of B.main(null)
. What I'm trying to do is, make it so that when the button is clicked, it will open window B but if clicked again it won't. Now, I can almost manage this just fine by simply setting a boolean value, but the problem is of course if I click once, the window opens and that's fine...but if I close window B and click the appropriate button in A again nothing happens...because the boolean is still saying that B is open.
So what I'm wondering is, given this kind of setup, is there a way that I could reset that boolean in A when B is closed? I was thinking mabe I could do something with a WindowListener
in B but if that is a possible solution then I till haven't figured out what to configure it to do..
Upvotes: 2
Views: 278
Reputation: 14164
Don't destroy B or set the reference to null, just hide it when closed. You can create it hidden on application startup, or just on-demand from A.
A.Button then calls --> B.show().
If B is a JFrame (which it probably should be) you can set the behaviour on close 'X' being clicked by calling JFrame.setDefaultCloseOperation()
. The default should already be WindowConstants.HIDE_ON_CLOSE
.
Upvotes: 2
Reputation: 2415
Basically what you have to do, is make one Frame your "main" frame, meaning it contains the main method. In your case that would be your Frame A. Then make Frame B (rather use JDialog instead of JFrame) part of Frame A.
Something like:
public MainApp extends JFrame { // Frame A
...
private static CustomWindowB FrameB = null;
...
public static void main(String[] args){
super();
FrameB = new CustomWindowB(...);
...
}
...
public void FunctionCalledByButtonClick(){
if(FrameB == null){
FrameB = new CustomWindowB(...);
} else {
if(FrameB.isVisible()){
FrameB.hide();
} else {
FrameB.show();
}
}
}
}
And for B you can do:
public CustomWindowB extends JDialog { // Frame B
public CustomWindowB(...){
super();
...
this.setVisible(true);
}
public void hide(){
this.setVisisble(false);
}
public void show(){
this.setVisisble(true);
}
}
Upvotes: 1