Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

java - 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...