java How to hide JPanel correctly

I want to hide one panel by clicking the Button, which will allow you to see another one I have this code

class MyWindow extends JFrame {
    public MyWindow (){
        setTitle("X/O");
        setBounds(300,300,400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        ImageIcon icon = new ImageIcon("icons.png");
        setIconImage(icon.getImage());

        JPanel mainPanel = new JPanel();                  //Создаю панели
        JPanel centerPanel = new JPanel();                                           
        JPanel bottomPanel = new JPanel();
        JPanel centerPanelWindowOne = new JPanel();
        JPanel centerPanelWindowTwo = new JPanel();

        mainPanel.setBackground(Color.blue);              //Цвета основных панелей
        centerPanel.setBackground(Color.white);
        bottomPanel.setPreferredSize(new Dimension(1,40));//Расположение остальных панелей
        centerPanel.add(centerPanelWindowOne);
        centerPanel.add(centerPanelWindowTwo);
        centerPanelWindowOne.setPreferredSize(new Dimension(400,40));
        centerPanelWindowTwo.setPreferredSize(new Dimension(400,40));

        add(mainPanel, BorderLayout.CENTER);              //Указываю компановку
        add(bottomPanel, BorderLayout.SOUTH);
        add(centerPanel, BorderLayout.CENTER);
        mainPanel.setLayout(new FlowLayout());
        centerPanel.setLayout(new FlowLayout());
        bottomPanel.setLayout(new GridLayout());
        centerPanelWindowOne.setLayout(new FlowLayout());
        centerPanelWindowTwo.setLayout(new FlowLayout());

        JButton start = new JButton("Старт");
        bottomPanel.add(start);
        JButton exit = new JButton("Выход");
        bottomPanel.add(exit);

        exit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        start.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                centerPanel.setVisible(false);

            }
        });


        setVisible(true);
    }
}

Total, after clicking the Start button, I want to close the visibility of the centrePanel, and see the mainPanel, according to my logic, I first create and show the mainPanel, and then the centrePanel, and when I use the button to specify the visibility false for the centrePanel, the mainPanel should be displayed, but after the start button, the centrePanel panel is closed, and there is nothing, how to implement it correctly?

Author: Vlad Zherihov, 2018-09-25

1 answers

The code is copied from here: https://pacificsimplicity.ca/blog/simple-state-switching-java-example-using-jpanels-and-jbuttons

Briefly the idea is as follows:

  • You need to create another JPanel and make it the main one, add it to the JFrame
  • You create as many panels as you need (preferably in the form of separate classes)
  • When you need to change the JPanel-just delete everything from the main panel, add the desired one and redraw, it is better to do more revalidate()

    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    enum ViewState {
        START_STATE, NEXT_STATE;
    }
    
    @SuppressWarnings("serial")
    class Panel2 extends JPanel {
        public Panel2() {
            JPanel  panel2 = new JPanel();
            JButton button = new JButton("sweet");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    MyWindowTest.changeState(ViewState.START_STATE);
                }
            });
            panel2.add(button);
            this.add(panel2);
        }
    }
    
    @SuppressWarnings("serial")
    class Panel1 extends JPanel {
        public Panel1() {
            JPanel panel1 = new JPanel();
            JButton button = new JButton("my button");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    MyWindowTest.changeState(ViewState.NEXT_STATE);
                }
            });
            panel1.add(button);
            this.add(panel1);
        }
    }
    
    public class MyWindowTest {
        private static ViewState viewState;
        private static JPanel mpanel;
        private static JPanel panel1;
        private static JPanel panel2;
        private static JFrame frame;
    
        public MyWindowTest() {
    
            frame = new JFrame();
            mpanel = new JPanel();
            panel1 = new Panel1();
            panel2 = new Panel2();
    
            // Sets default state
            changeState(ViewState.START_STATE);
    
            frame.setSize(100, 100);
            frame.add(mpanel);
            frame.setVisible(true);
        }
    
        public static void changeState(ViewState state) {
            viewState = state;
            System.out.println("change state: " + viewState);
    
            switch (state) {
                case START_STATE:
                    mpanel.removeAll();
                    mpanel.add(panel1);
                    mpanel.revalidate();
                    mpanel.repaint();
                    break;
                case NEXT_STATE:
                    mpanel.removeAll();
                    mpanel.add(panel2);
                    mpanel.revalidate();
                    mpanel.repaint();
                    break;
                default:
                    System.out.println("UNKNOWN STATE!");
                    break;
            }
        }
    
        public static void main(String[] args) {
            @SuppressWarnings("unused")
            MyWindowTest n = new MyWindowTest();
    
        }
    
    }
    
 1
Author: Axenow, 2018-09-25 12:08:24