What is the proper way to swap out an existing JPanel in a JFrame with another?(将 JFrame 中的现有 JPanel 换成另一个 JPanel 的正确方法是什么?)
问题描述
我正在构建一个程序,该程序需要将当前可见的 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.
这篇关于将 JFrame 中的现有 JPanel 换成另一个 JPanel 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 JFrame 中的现有 JPanel 换成另一个 JPanel 的正确方法是什么?
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01