Search code examples
javaswingjframedispose

close 1 jframe with multiple jframes active not working


My program displays some windows (jframe and jpanel) on the screen and a main frame. When the user select the option to delete one of these windows in the main frame, it should close the selected window.

I have those windows in an array. When the user select the window to close, it will erase that jframe and it's jpanel from the array and it should close that jframe, but it doesn't. There are no errors showned and when I run the program again, everything is as it is suposed to be: the deleted frame isn't showed. My conclusion is i'm not working correctly with closing the jframe, and the rest of the program is fine.

i have tried:

windows[Frame_to_close].setDefaultCloseOperation(windows[Frame_to_close].DISPOSE_ON_CLOSE );

and

windows[Frame_to_close].setVisible(false); 
windows[Frame_to_close].dispose();

Am I doing anything wrong when closing the window? Is there any other way of closing a window(Jframe and Jpanel)?


Solution

  • How will the user select the window to close? Using the code below, you can close a window by pressing a button or close the window directly (in which case the frame will not be removed from the list):

    private void createManyFrames() {
        final JFrame mainFrame = new JFrame("Stack Overflow: closing frames");
        mainFrame.setBounds(100, 100, 240, 600);
        mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        mainFrame.getContentPane().setLayout(new FlowLayout());
        final List<JFrame> frames = initializeFrames(Arrays.asList("one", "two", "three"));
        for (final JFrame frame : frames) {
            final JButton button = new JButton(frame.getTitle());
            mainFrame.getContentPane().add(button);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(final ActionEvent e) {
                    frame.dispose();
                    frames.remove(frame);
                }
            });
            frame.setVisible(true);
        }
        mainFrame.setVisible(true);
    }
    
    private List<JFrame> initializeFrames(final List<String> frameNames) {
        final List<JFrame> frames = new ArrayList<JFrame>();
        for (final String frameName : frameNames) {
            final JFrame frame = new JFrame(frameName);
            frame.setBounds(480, 120 * (1 + frames.size()), 200, 100);
            final JPanel panel = new JPanel();
            panel.add(new JLabel("Label in panel in frame " + frameName + "."));
            frame.getContentPane().add(panel);
            frames.add(frame);
        }
        return frames;
    }