Search code examples
javaswingborderlayout-managergrid-layout

How to set the margin in GridLayout's first Column?


I want the margin from the left side in Grid layout first column only. The Jlabel in the first column is LEFT aligned.

image of the problem

Code for the Row is

 lbl1 = new JLabel("Hold");
       lbl1 .setFont(new Font("Arial Black", Font.PLAIN, text));
       lbl1 .setHorizontalAlignment(SwingConstants.LEFT);
       lbl1 .setForeground(Color.decode(textColor));
       panel1.add(lbl1 );


       lbl2= new JLabel("100");
       lbl2.setFont(new Font("Arial Black", Font.PLAIN, text));
       lbl2.setHorizontalAlignment(SwingConstants.CENTER);
       lbl2.setForeground(Color.decode(textColor));
       panel1.add(lbl2);

Code for the panel is

setLayout(new GridLayout(0,2));

Solution

  • In your case you can set an empty border for all your "left" label.

    lb1.setBorder(new EmptyBorder(0, 10, 0, 0));
    

    This code will provide 10 points offset from the left side of the label.

    Usually GridLayout is not a best choice for your purposes. I would advise you to look for another layout manager. The standard GridBagLayout is a little bit too verbouse so it would be better to learn a third-party layout like MigLayout or FormLayout.