user6416322
user6416322

Reputation: 1

Removing/Replacing JFrame window?

I want to replace a JFrame (which contains a JPanel) if the user types the letter "N".

My current code just adds a new JFrame but doesn't remove the previous one.

Here is my Frame.java class:

public class Frame extends JFrame {
    public Frame() {
        add(new Panel());
        pack();
    }

    public static void main(String[] args) {
        JFrame frame = new Frame();
        frame.setVisible(true);
    }
}

And here is my Panel.java class:

public class Panel extends JPanel implements ActionListener {

    public Panel() {
        setPreferredSize(new Dimension(1000, 1000));
        setFocusable(true);

        addKeyListener(new PanelKeyListener());
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Paint things
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }

    class PanelKeyListener implements KeyListener {

        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();

            switch (keyCode) {
                case KeyEvent.VK_N:
                    JFrame frame = new Frame();
                    frame.setVisible(true);
                    break;
             }
        }
    }
}

Upvotes: 0

Views: 658

Answers (1)

Alexis Clarembeau
Alexis Clarembeau

Reputation: 2964

If you really want to replace the JFrame, you can open a new one and close it with:

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

Or by:

frame.setVisible(false); 
frame.dispose(); 

But, it's very strange to replace a JFrame. Usually, we change the content of the frame (with setContentPanel) and not the frame itself :)

frame.setContentPanel(new OtherPanel())

Personnaly, I would change your code to:

public class Frame extends JFrame {
    public static void main(String[] args) {
        JFrame frame = new Frame();
        frame.setContentPane(new MyPanel(frame)); 
        frame.setVisible(true);
    }
}

public class MyPanel extends JPanel implements ActionListener {
    private Frame refFrame; 
    public MyPanel(Frame frame) {
        this.refFrame = frame; 

        setPreferredSize(new Dimension(1000, 1000));
        setFocusable(true);

        addKeyListener(new PanelKeyListener());
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Paint things
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }

    class PanelKeyListener implements KeyListener {

        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();

            switch (keyCode) {
                case KeyEvent.VK_N:
                    refFrame.setContentPane(new OtherPanel()); 
                    break;
             }
        }
    }
}

Upvotes: 1

Related Questions