How do i find if a window is opened on swing

前端 未结 3 1024
夕颜
夕颜 2020-12-30 11:48

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

相关标签:
3条回答
  • 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;
        }
    
    0 讨论(0)
  • 2020-12-30 12:30

    simply check if the other window is open before closing with window.isVisible();

    0 讨论(0)
  • 2020-12-30 12:34

    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.

    0 讨论(0)
提交回复
热议问题