Reputation: 1066
I've got an application in which sometimes I use "modal", smaller windows. To simulate such modal behaviour what I do is defining them as extensions of JFrames, disabling the main application frame and setting the default close operation to do nothing. The problem of this is that JFrame can't have a parent so, when the user clicks the button said to close the window, it in fact closes and the system goes back to the last used application, which is not always the desired effect (e.g. the user opens the modal window, then he/she Alt+Tabs into another application, then switches back into the modal window and closes it, resulting this in being presented this last application, instead the main frame of mine). Is there any way to do this (binding JFrame to a parent or something like that...?). Note that JOptionPane is not an option because these smaller windows need to have like twenty different and custom Components inside each.
Upvotes: 0
Views: 129
Reputation: 562
You could add a JFrame parameter to the constructor and internally save it as parent, and save a reference of the child in a list in the parent. Then you can override the dispose method and close all children/parent before closing the window.
For example:
public class ParentWindow extends JFrame {
//Here you add children when you create them
List<JFrame> children = new ArrayList<JFrame>();
@Override
public void dispose() {
for(JFrame f : children) {
f.dispose();
}
super.dispose();
}
public void randomMethod() {
JFrame newWindow = new JFrame(this);
children.add(newWindow);
}
}
public class ChildWindow extends JFrame {
//Here you save the parent window
JFrame parent;
public ChildWindow(JFrame parent) {
this.parent = parent;
}
@Override
public void dispose() {
parent.dispose();
super.dispose();
}
}
Upvotes: 0