[英]Why isn't this CardLayout showing up?
I'm making a program that's supposed to be multi-function, so I'm using CardLayout to show each function/JPanel at a time. 我正在创建一个应该是多功能的程序,所以我使用CardLayout一次显示每个函数/ JPanel。 However, it's just showing a blank screen the moment I run it.
但是,它只是在我运行它时显示一个空白屏幕。 I can't get to show the "Index" panel of the CardLayout.
我无法显示CardLayout的“索引”面板。 Here's my code:
这是我的代码:
public class Window {
static JFrame frame = new JFrame("Utilities");
static JPanel windowContent = new JPanel();
static JPanel index = new JPanel();
static JPanel panel1 = new JPanel();
static JPanel panel2 = new JPanel();
static JPanel panel3 = new JPanel();
static JButton panel1Button = new JButton("Panel 1");
static JButton panel2Button = new JButton("Panel 2");
static JButton panel3Button = new JButton("Panel 3");
public static void GUI(){
CardLayout cl = new CardLayout();
GridBagLayout gl = new GridBagLayout();
GridBagConstraints c1,c2,c3;
c1 = new GridBagConstraints();
c2 = new GridBagConstraints();
c3 = new GridBagConstraints();
windowContent.setLayout(cl);
index.setLayout(new BoxLayout(index, BoxLayout.PAGE_AXIS));
panel1.setLayout(gl);
panel2.setLayout(gl);
panel3.setLayout(gl);
panel1.setBackground(Color.RED);
panel2.setBackground(Color.BLUE);
panel3.setBackground(Color.GREEN);
index.setBackground(Color.ORANGE);
windowContent.add(index, "Index");
windowContent.add(panel1, "Panel 1");
windowContent.add(panel2, "Panel 2");
windowContent.add(panel3, "Panel 3");
index.add(panel1Button);
index.add(panel2Button);
index.add(panel3Button);
IndexEngine IEngine = new IndexEngine();
panel1Button.addActionListener(IEngine);
panel2Button.addActionListener(IEngine);
panel3Button.addActionListener(IEngine);
c1.gridx = 0;
c1.gridy = 0;
frame.setSize(500, 500);
frame.setDefaultCloseOperation(1);
frame.setVisible(true);
cl.show(windowContent, "Index");
}
public static void main(String[] args) {
new Window();
GUI();
}
}
I don't see where you add the panel to the frame. 我没有看到您将面板添加到框架的位置。 I would guess you need code like the following:
我猜您需要以下代码:
//frame.setSize(500, 500);
frame.add(windowContent);
frame.pack();
Also, the entire structure of you code is wrong. 此外,您的代码的整个结构是错误的。 You should NOT be using static methods and variables.
您不应该使用静态方法和变量。 I suggest you read the section from the Swing tutorial on How to Use Card Layout for a working example with a card layout and so see how to better structure your program.
我建议你阅读Swing教程中关于如何使用卡片布局的部分, 以获得卡片布局的工作示例,以便了解如何更好地构建程序。
Take a look at other demo programs from other sections as well, for example How to Use Labels
because the demo there show a different structure for you code by extending a JPanel which may even be easier to follow. 看看其他部分的其他演示程序,例如
How to Use Labels
因为那里的演示通过扩展JPanel为您的代码显示了不同的结构,甚至可能更容易理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.