Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

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

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.

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();  
}

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

that requires swapping out the current, visible JPanel with another

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...