如何让 JLabels 和 JTextAreas 对齐到屏幕的左上角而不是中心

How to get the JLabels and JTextAreas to align to the top left of the screen not the center

public Panel(){
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

    c.insets = new Insets(10,10,10,10);

    c.gridx = 0;
    c.gridy = 0;

    add(l1 , c);

    c.gridx = 1;
    c.gridy = 0;

    add(tf1 , c);

    c.gridx = 0;
    c.gridy = 1;

    add(l2 , c );

    c.gridx = 1;
    c.gridy = 1;

    add(tf2 , c);
}

这是目前的样子:

如何将内容对齐到左上角?

尝试在 c 声明后添加以下行:

c.anchor = GridBagConstraints.NORTHWEST;

像这样使用下面的 JPanel:

add(new JPanel(), new GridBagConstraints(0,2,2,1,1.0,1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2,2,2,2),1,1));

使用锚点,它们是 GridBagConstraints class 的一部分,用于告诉 Java 组件去哪里。因此,例如,如果您希望它们出现在左上角,您只需使用:

c.anchor = GridBagConstraints.LINE_START;

您也可以使用

c.anchor = GridBagConstraints.NORTHWEST;

虽然我更喜欢第一个。您可以在 Oracle 文档中阅读更多相关信息并查看所有可用选项 here

还有一点,如果你不给 weighty 赋值,锚点将无法工作。如果你不指定一个值,因为 Java 表示所有组件将聚集在中心。 Weighty 可以取 0 到 1 之间的值。例如:

c.weighty = 0.5;