问题描述
我正在构建一个程序,该程序需要将当前可见的JPanel与另一个交换.不幸的是,似乎有很多事情要做,而我所有的尝试都以失败告终.我可以成功地使第一个JPanel出现在我的JFrame中,但是交换JPanels会导致空白的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!
推荐答案
that requires swapping out the current, visible JPanel with another
有关完整示例,请查看 CardLayout .如何正确执行.
Have a look at CardLayout for a complete example of how to do it properly.
这篇关于将一个JFrame中的现有JPanel与另一个JPanel换出的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!