Why doesn't setLocation() move my label?

倖福魔咒の 提交于 2019-11-27 16:18:26

问题


I have the following code where I try to place a JLabel in a custom location on a 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.


回答1:


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

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:

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.

Here is a great tutorial on getting started with using LayoutManagers.

If you must go without a LayoutManager here is a good tutorial for going without one.




回答2:


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.



来源:https://stackoverflow.com/questions/3695673/why-doesnt-setlocation-move-my-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!