Java 为什么 setLocation() 不移动我的标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3695673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:35:32  来源:igfitidea点击:

Why doesn't setLocation() move my label?

javaswinglayout-manager

提问by rob

I have the following code where I try to place a JLabelin a custom location on a JFrame.

我有以下代码,我尝试将 aJLabel放在JFrame.

public class GUI extends JFrame 
{

    /**
     * 
     * @param args
     */
    public static void main(String args[]) 
    {
        new GUI();
    }
    /**
     * 
     */
    public GUI() 
    {
        JLabel addLbl = new JLabel("Add: ");
        add(addLbl);
        addLbl.setLocation(200, 300);
        this.setSize(400, 400);

        // pack();
        setVisible(true);
    }
}

It doesn't seem to be moving to where I want it.

它似乎没有移动到我想要的地方。

采纳答案by jjnguy

The problem is that the LayoutManagerof the panel is setting the location of the label for you.

问题是LayoutManager面板的 正在为您设置标签的位置。

What you need to do is set the layout to null:

您需要做的是将布局设置为空:

public GUI() {
    setLayout(null);
}

This will make it so the frame does not try to layout the components by itself.

这将使框架不会尝试自行布局组件。

Then call setBounds(Rectangle)on the label. Like so:

然后调用setBounds(Rectangle)标签。像这样:

addLbl.setBounds(new Rectangle(new Point(200, 300), addLbl.getPreferredSize()));

This should place the component where you want it.

这应该将组件放置在您想要的位置。

However, if you don't have a really great reason to lay out the components by yourself, it's usually a better idea to use LayoutManagersto work in your favor.

但是,如果您没有充分的理由自己布置组件,那么使用LayoutManagers对您有利的工作通常是一个更好的主意。

Hereis a great tutorial on getting started with using LayoutManagers.

是一个关于开始使用LayoutManagers的很棒的教程。

If you must go without a LayoutManagerhereis a good tutorial for going without one.

如果你必须不带,LayoutManager这里是一个很好的教程,可以不带。

回答by TheRayKid101

You put the location code under the frame and it will work but if you want it to work for sure put the location code in a run while loop. That's what I did to figure it out and it works.

您将位置代码放在框架下,它会起作用,但如果您确实希望它起作用,请将位置代码放入 run while 循环中。这就是我为弄清楚它所做的并且它有效。