What is the proper way to swap out an existing JPanel in a JFrame with another?

后端 未结 3 1013
天涯浪人
天涯浪人 2020-12-22 04:00

I\'m building a program that requires swapping out the current, visible JPanel with another. Unfortunately there seems to be multiple to go about this and all of my attempts

3条回答
  •  执念已碎
    2020-12-22 04:34

    You should do .setVisible(false); to the panel which you want to be replaced.

    Here is a working example, it switches the panels when you press "ENTER"; If you copy this in an IDE, automatically get the imports (shift+o in Eclipse);

    public class MyFrame extends JFrame implements KeyListener {
    
        private JButton button = new JButton("Change Panels");
        private JPanel panelOnFrame = new JPanel();
        private JPanel panel1 = new JPanel();
    
        public MyFrame() {
            // adding labels to panels, to distinguish them
            panelOnFrame.add(new JLabel("panel on frame"));
            panel1.add(new JLabel("panel 1"));      
    
            setSize(new Dimension(250,250));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            add(button);
            add(panelOnFrame);
            setVisible(true);
            addKeyListener(this);
    
            addKeyListener(this);
            setFocusable(true);
        }
    
        public static void main(String[] args) {
            MyFrame frame = new MyFrame();
        }
    
        @Override
        public void keyPressed(KeyEvent k) {
            if(k.getKeyCode() == KeyEvent.VK_ENTER){
    

    //+-------------here is the replacement:

                panelOnFrame.setVisible(false);
                this.add(panel1);
            }
        }
    
        @Override
        public void keyReleased(KeyEvent arg0) {
        }
    
        @Override
        public void keyTyped(KeyEvent arg0) {
        }
    }
    

提交回复
热议问题