我应该如何使用 GridBagLayout 使 JComponents 像 FlowLayout.Left 一样对齐

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

我正在使用 GridBagLayout ,我希望我的组件从左到右布局,就像在 FlowLayoutFlowLayout.LEFT 中一样。 下图解释了我所拥有的(左侧)以及我的目标。 (右边)

这是我为此编写的一些代码。在尝试(未成功)找出解决方案时使用了注释行:

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);
    }

}

感谢用户 camickr 我发现:

anchor GridBagConstraints

的属性

当组件小于其显示区域时使用,以确定放置组件的位置(区域内)。

并且正确设置为:

 gbc.anchor = GridBagConstraints.WEST;

但这还不够,因为:

weightxweighty GridBagConstraints

属性

权重用于决定space如何在列之间(weightx)和行之间(weighty)分配;这对于指定调整大小行为很重要。 除非您为 weightx 或 weighty 指定至少一个非零值,否则所有组件都会聚集在其容器的中心。

在添加 JComponent 之前给它一个介于 0.1 和 1 之间的值,它将起作用:

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

谢谢大家