将 JFrame 中的现有 JPanel 换成另一个 JPanel 的正确方法是什么?

2022-01-24 00:00:00 java swing jpanel jframe

我正在构建一个程序,该程序需要将当前可见的 JPanel 换成另一个.不幸的是,似乎有很多事情要做,我所有的尝试都以失败告终.我可以成功地让第一个 JPanel 出现在我的 JFrame 中,但是交换 JPanel 会导致一个空白 JFrame.

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 have ended in failure. I can successfully get the first JPanel to appear in my JFrame, but swapping JPanels results in a blank JFrame.

我的主要 JFrame:

My Main JFrame:

public class ShellFrame {

static CardLayout cl = new CardLayout(); //handles panel switching
static JFrame frame; //init swing on EDT
static MainMenu mm; 
static Panel2 p2;
static Panel3 p3;

public static void main(String[] args) {
    initFrame();
}

public static void initFrame() {
    SwingUtilities.invokeLater(new Runnable() {
         public void run() {
              frame = new JFrame();
              frame.setDefaultCloseOperation(3);
              frame.setLayout(cl);

              mm = new MainMenu();
              pp = new PlacementPanel();

              //first panel added to frame will always show first
              frame.add(mm, "MainMenu");
              frame.pack(); //sizes frame to fit the panel being shown
              frame.setVisible(true);
         }
    });
}

public static void switchPanel(String name) {
    cl.show(frame.getContentPane(), name);
    frame.pack();
}

public static void updatePanel2(/* args */) {
   frame.removeAll();
   p2 = new Panel2(/* args */);
   frame.add(pp, "PlacementPanel");
   frame.pack();
   frame.validate();
   frame.repaint();  
}

我正在尝试使用 updatePanel2 将现有面板换成新的 Panel2,但它似乎不起作用.Panel2 本身可以正常工作,但尝试将它与我的程序结合使用只会产生一个空白窗口.任何帮助将不胜感激!

I'm trying to use updatePanel2 to swap out the existing panel with a new Panel2 but It doesn't seem to be working. Panel2 works fine on it's own but trying to use it in conjunction with my program simply yields a blank window. Any help would be greatly appreciated!

推荐答案

需要将当前可见的 JPanel 换成另一个

查看 CardLayout 的完整示例如何正确地做到这一点.

Have a look at CardLayout for a complete example of how to do it properly.

相关文章