简体   繁体   English

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

[英]Why doesn't setLocation() move my label?

I have the following code where I try to place a JLabel in a custom location on a JFrame .我有以下代码,我尝试将JLabel放在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.它似乎没有移动到我想要的地方。

The problem is that the LayoutManager of 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.然后在标签上调用setBounds(Rectangle) Like so:像这样:

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 LayoutManagers to work in your favor.但是,如果您没有充分的理由自己布置组件,那么使用LayoutManagers来为您工作通常是一个更好的主意。

Here is a great tutorial on getting started with using LayoutManager s. 是一个关于开始使用LayoutManager的很棒的教程。

If you must go without a LayoutManager here is a good tutorial for going without one.如果你必须不使用LayoutManager 这里是一个很好的教程,可以不使用LayoutManager

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.您将位置代码放在框架下,它会起作用,但如果您希望它确实起作用,请将位置代码放入 run while 循环中。 That's what I did to figure it out and it works.这就是我所做的来弄清楚它并且它有效。

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

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