Search code examples
javaswingalignmentgridbaglayout

How should I use a GridBagLayout to have JComponents aligned like FlowLayout.Left


I'm using the GridBagLayout , and I'd like to have my component layed out from left to the right like in a FlowLayout with FlowLayout.LEFT. Following image explain what i have (on the left), and what I am aiming for. (on the right)

MiMage

Here is some code I wrote for that purpose. Commented line have been used while tring to (unsucesfully) figure out the solution:

public class Main {
    public static void main(String[] args)  {   
        SwingUtilities.invokeLater(new Demo());     
    }
}

class Demo implements Runnable{
    @Override
    public void run() {
        JFrame frame = new JFrame();
        frame.setLocationRelativeTo(null);
        frame.setMinimumSize(new Dimension(250,100));

        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createLineBorder(Color.black));
        panel.setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(0,10,0,0);
        gbc.anchor = GridBagConstraints.EAST;
        JLabel label1 = new JLabel("MyLabel1"); 
//      JLabel label1 = new JLabel("MyLabel1",SwingConstants.LEFT); 
//      label1.setHorizontalAlignment(SwingConstants.LEFT);
//      gbc.fill=GridBagConstraints.HORIZONTAL;
//      gbc.ipadx = 60;
//      gbc.ipady = 10;
        panel.add(label1,gbc);

        JLabel label2 = new JLabel("MyLabel2"); 
        panel.add(label2,gbc);

        frame.add(panel);
        frame.setVisible(true);
    }

}

Solution

  • Thanks to user camickr i found that:

    anchor attribute of GridBagConstraints

    Used when the component is smaller than its display area to determine where (within the area) to place the component.

    and this is properly set to:

     gbc.anchor = GridBagConstraints.WEST;
    

    but it is not enough, since:

    weightx and weighty attribute of GridBagConstraints

    Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty); this is important for specifying resizing behavior. Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container.

    give it a value between 0.1 and 1 before adding JComponent and it will works:

       gbc.weightx = 0.1; //0.1 works well in my case since frame can't be resized
    

    Thanks everyone.