我正在创建一个应该是多功能的程序,所以我使用CardLayout一次显示每个函数/ JPanel。但是,它只是在我运行它时显示一个空白屏幕。我无法显示CardLayout的“索引”面板。这是我的代码:
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();
}
}
答案 0 :(得分:2)
我看不到您将面板添加到框架的位置。我猜您需要以下代码:
//frame.setSize(500, 500);
frame.add(windowContent);
frame.pack();
此外,您的代码的整个结构是错误的。您不应该使用静态方法和变量。我建议您阅读How to Use Card Layout上Swing教程中的部分,了解卡布局的工作示例,以便了解如何更好地构建程序。
看一下其他部分的其他演示程序,例如How to Use Labels
,因为那里的演示通过扩展JPanel为你的代码显示了不同的结构,甚至可能更容易理解。