Problem with Java GridBagConstraints

So, I need my layout to look like this:

{|Name|         |Info||Tag||Id|}

Right now it looks like this:

{|Name|   |Info|   |Tag|   |Id|}

More or less. Here is my code:

    GridBagConstraints c;

    c = new GridBagConstraints(0, 0, 5, 1, .5, .1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0,0,0,0), 5, 5);
    header.add(name, c);
    c = new GridBagConstraints(10, 0, 1, 1, .5, .1, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(1,1,1,1), 5, 5);
    header.add(id, c);
    c = new GridBagConstraints(8, 0, 2, 1, .5, .1, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(1,1,1,1), 5, 5);
    header.add(tag, c);
    c = new GridBagConstraints(6, 0, 2, 1, .5, .1, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(1,1,1,1), 5, 5);
    header.add(info, c);

How should I change this to get the desired result?

Answer

A horizontal BoxLayout might be easier. Your code would be something like:

header.add( name );
header.add( Box.createHorizontalGlue() );
header.add( info );
...

EXAMPLE

public class GridBagLayoutTest{

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                createAndShowGUI();             
            }
        });
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);

        final JPanel panel = new JPanel(){
            @Override
            public Dimension getPreferredSize(){
                return new Dimension(200, 20);
            }
        };
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
        panel.add( new JLabel("|Name|"));
        panel.add(Box.createHorizontalGlue());
        panel.add(new JLabel("|Info|"));
        panel.add(new JLabel("|Tag|"));
        panel.add(new JLabel("|Id|"));

        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

OUTPUT

enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *