How can I replace one of two JPanels with another JPanel in Java?

前端 未结 3 469
小蘑菇
小蘑菇 2021-01-24 08:48

I designed an interface for the welcome screen with one JFrame included two JPanels (JPanel1 on right and JPanel2 on left). The buttons on the left is to switch the Panels in JP

3条回答
  •  悲哀的现实
    2021-01-24 09:33

    An alternative to CardLayout would be JRootPane and its JRootPane.setContentPane() method. Here's an example:

    final JPanel panel1 = ...;
    final JPanel panel2 = ...;
    boolean showingPanel1 = true;
    final JRootPane rootPane = new JRootPane();
    rootPane.setContentPane(panel1);
    JButton switchButton = new JButton("Switch");
    switchButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            if (showingPanel1) {
                rootPane.setContentPane(panel2);
            } else {
                rootPane.setContentPane(panel1);
            }
            showingPanel = !showingPanel;
        }
    });
    

    Add the rootPane and switchButton components to your window, and then clicking switchButton will switch out the panels.

    Here's a tutorial. You should mostly be concerned with JRootPane.setContentPane, the other stuff in the tutorial isn't relevant.

提交回复
热议问题