Search code examples
javaswinguser-interfacelayout-managergridbaglayout

GridBagLayout Troubleshooting


So I decided to make my GUI look a bit nicer, and use GridBagLayout instead. The following are the objects I am adding to my panel:

choosePanel = new JPanel();
choosePanel.setLayout(new GridBagLayout());

chooseLabel = new JLabel("Choose a quarter to input data for:");
addItem(chooseLabel, 0, 0, 1, 1);

qGroup = new ButtonGroup();

    q1 = new JRadioButton("Q1");
    qGroup.add(q1);
    q1.setSelected(true);
    addItem(chooseLabel, 0, 1, 1, 1);

    q2 = new JRadioButton("Q2");
    qGroup.add(q2);
    addItem(chooseLabel, 0, 2, 1, 1);

    q3 = new JRadioButton("Q3");
    qGroup.add(q3);
    addItem(chooseLabel, 0, 3, 1, 1);

    q4 = new JRadioButton("Q4");
    qGroup.add(q4);
    addItem(chooseLabel, 0, 4, 1, 1);

chooseButton = new JButton("Press to Enter Quarter");
    chooseButton.addActionListener(e->{
        cl.show(mainPanel, "Info");
        this.setSize(330, 240);
    });
    chooseButton.setPreferredSize(new Dimension(200, 100));
    addItem(chooseLabel, 1, 1, 1, 1);

    resetButton = new JButton("Reset all previous data");
    resetButton.addActionListener(e->{

    });
    resetButton.setPreferredSize(new Dimension(200, 100));
    addItem(chooseLabel, 1, 2, 1, 1);

And here is the "addItem" method:

private void addItem(JComponent c, int x, int y, int width, int height){
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = width;
    gbc.gridheight = height;
    gbc.weightx = 100.0;
    gbc.weighty = 100.0;
    gbc.fill = GridBagConstraints.NONE;
    choosePanel.add(c, gbc);
}

My problem is, when I run the program, all that shows is the chooseLabel in the middle of the screen, and nothing else. Anyone know how to fix this? ......


Solution

  • Change

    q1 = new JRadioButton("Q1");
    qGroup.add(q1);
    q1.setSelected(true);
    addItem(chooseLabel, 0, 1, 1, 1);
    
    q2 = new JRadioButton("Q2");
    qGroup.add(q2);
    addItem(chooseLabel, 0, 2, 1, 1);
    
    q3 = new JRadioButton("Q3");
    qGroup.add(q3);
    addItem(chooseLabel, 0, 3, 1, 1);
    
    q4 = new JRadioButton("Q4");
    qGroup.add(q4);
    addItem(chooseLabel, 0, 4, 1, 1);
    

    to

    q1 = new JRadioButton("Q1");
    qGroup.add(q1);
    q1.setSelected(true);
    addItem(q1 , 0, 1, 1, 1);
    
    q2 = new JRadioButton("Q2");
    qGroup.add(q2);
    addItem(q2, 0, 2, 1, 1);
    
    q3 = new JRadioButton("Q3");
    qGroup.add(q3);
    addItem(q3, 0, 3, 1, 1);
    
    q4 = new JRadioButton("Q4");
    qGroup.add(q4);
    addItem(q4, 0, 4, 1, 1);
    

    and so on.. You are adding chooseLabel all the time.