简体   繁体   English

如何使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);
}

This what it currently looks like: 这是当前的样子: 在此处输入图片说明

How do I align the content to the top left? 如何将内容对齐到左上方?

Use anchors, they are part of GridBagConstraints class and they are used to tell Java where do components go. 使用锚点,它们是GridBagConstraints类的一部分,用于告诉Java组件在哪里。 So for example if you want them to appear on the left top corner you just use: 因此,例如,如果您希望它们显示在左上角,则可以使用:

c.anchor = GridBagConstraints.LINE_START;

You could also use 您也可以使用

c.anchor = GridBagConstraints.NORTHWEST;

Altough I like more the first one. 虽然我更喜欢第一个。 You can read more about this and see all the available options here at Oracle Documentation. 您可以阅读有关此内容的更多信息,并在Oracle文档中查看此处的所有可用选项。

One thing more, anchors won't work if you don't give a value to weighty. 还有一件事,如果您不给weighty值,锚将无法工作。 If you don't asign a value as Java says all components will clump together on the center. 如果您不按Java所述分配任何值,则所有组件都将集中在中间。 Weighty can take values from 0 to 1. For example: 加权值可以取0到1之间的值。例如:

c.weighty = 0.5;

尝试在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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM