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 keep at-least one window open all the time so that the application does not hides without closed fully. If you don't understand read the following scenario:
I have window A and window B opened at the same time. Now i can close either window A or Window B but not both. In other words window B should be allowed to close only if window A is opened and vice versa. How do i do this in swing ??
To determine when a Window is opened in Java, use the WindowListener, which is the listener interface for receiving window events..
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With