How do i find if a window is opened on swing

Deepak picture Deepak · May 5, 2011 · Viewed 9.7k times · Source

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 ??

Answer

kleopatra picture kleopatra · May 5, 2011

A simple kind-of windowManger is not really tricky, all you need is

  • WindowListener which keeps tracks of the Windows it's listening to
  • a defined place to create the windows and register the the listener
  • make the windows do-nothing-on-close and make the listener responsible for the decision of whether to close or not (will do so for all except the last)

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;
    }