I have a problem with my application where the user will open more than one window at a time. And i have added dispose() method to call on closing the window. Now i should k
A simple kind-of windowManger is not really tricky, all you need is
Some snippet:
// the listener (aka: WindowManager)
WindowListener l = new WindowAdapter() {
List<Window> windows = new ArrayList<Window>();
@Override
public void windowOpened(WindowEvent e) {
windows.add(e.getWindow());
}
@Override
public void windowClosing(WindowEvent e) {
if (windows.size() > 1) {
windows.remove(e.getWindow());
e.getWindow().dispose();
}
}
};
// create the first frame
JFrame frame = createFrame(l);
frame.setVisible(true);
// a method to create a new window, config and add the listener
int counter = 0;
private JFrame createFrame(final WindowListener l) {
Action action = new AbstractAction("open new frame: " + counter) {
@Override
public void actionPerformed(ActionEvent e) {
JFrame frame = createFrame(l);
frame.setVisible(true);
}
};
JFrame frame = new JFrame("someFrame " + counter++);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.add(new JButton(action));
frame.addWindowListener(l);
frame.pack();
frame.setLocation(counter * 20, counter * 10);
return frame;
}
simply check if the other window is open before closing with window.isVisible();
Just a possible approach...
Create a class, call it WindowManager
, that manages creation and disposal of windows.
It could for example retain the count of the windows currently open, and allow a dispose operation only if there are more than one windows "alive", otherwise show a confirm message with JOptionPane
telling the user "Really close? That would terminate the application." or something like that.
The "tricky" part is that you have to do this kind of window-related operations throughout the WindowManager
, otherwise everything would screw up.
Dunno if Swing has something like this built-in, I've never seen such a scenario.