I'm new to Java Swing and I have to code an Interface That looks like this:
It's a checkbox followed by a text field and then a button. Don't mind the dashed lines, I added them just to make the "grid" visible and I do understand I can just make a component and reuse for the checkbox, text and button so the layout would be way simpler. I'm just trying to understand the quirks of the GridbagLayout.
Basically the first row should have 2 columns and the second and third should have 6 columns. To do so I'm trying to use GridBagLayout, but the result is not the expected and I'm not sure if I'm missing something or if it's not possible to do this without inner panels. This is my class:
import javax.swing.*;
import java.awt.*;
public class GridBagLayoutTest extends JFrame {
JPanel panel = new JPanel();
public GridBagLayoutTest(){
setTitle("Grid Bag Layout Test");
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
setLayout(new GridBagLayout());
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx=1; // set to use all horizontal space available
gbc.weighty=0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(2,2,2,2);
// Labels line. Each label should be 50%
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new JLabel("Label 1"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
panel.add(new JLabel("Label 2"), gbc);
// Checkbox left group. The three components should take 50% of the total width
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(new JCheckBox("Ind 1"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(new JTextField(), gbc);
gbc.gridx = 2;
gbc.gridy = 1;
panel.add(new JButton("..."), gbc);
// Checkbox right group. The three components should take 50% of the total width
gbc.gridx = 3;
gbc.gridy = 1;
panel.add(new JCheckBox("Ind 1"), gbc);
gbc.gridx = 4;
gbc.gridy = 1;
panel.add(new JTextField(), gbc);
gbc.gridx = 5;
gbc.gridy = 1;
panel.add(new JButton("..."), gbc);
setContentPane(panel);
this.setSize(800,200 );
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
If it's possible to achieve this without inner panels, what am I missing in my code?
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new JLabel("Label 1"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
panel.add(new JLabel("Label 2"), gbc);
Your second label should start in column 3:
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new JLabel("Label 1"), gbc);
gbc.gridx = 3; // changed
gbc.gridy = 0;
panel.add(new JLabel("Label 2"), gbc);