Question

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. 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. 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();
}

}
Was it helpful?

Solution

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top