2013-12-15 79 views
0

我正在制作一个应该是多功能的程序,所以我使用CardLayout来一次显示每个函数/ JPanel。但是,当我运行它时,它只是显示一个空白屏幕。我无法显示CardLayout的“索引”面板。这里是我的代码:为什么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(); 
} 

} 

回答

2

我没有看到你将面板添加到框架的位置。我猜你需要如下代码:

//frame.setSize(500, 500); 
frame.add(windowContent); 
frame.pack(); 

此外,你的代码的整个结构是错误的。你不应该使用静态方法和变量。我建议你阅读How to Use Card Layout的Swing教程中的部分,了解卡片布局的一个工作示例,然后了解如何更好地构建程序。

看看其他部分的其他演示程序,例如How to Use Labels,因为那里的演示通过扩展一个JPanel来展示不同的结构,这个JPanel可能更容易遵循。

+0

感谢您对我的结构的反馈,我真的不擅长这一点。我使用静态变量的原因是让他们转移到另一个类。当他们不是静止的时候,他们不能被发现。任何想法,我做错了什么? – VirusParadox

+0

查看教程中的各种示例。您可以定义实例变量,然后使用getter/setter方法访问变量。 – camickr

+0

哇。刚才(在提问之后),我看了这个问题,我意识到要花多长时间才能意识到我的程序出了什么问题。每当我使用swing时,我都会记住这个问题。非常感谢! – VirusParadox