How do I move a component in a frame while I am using a layout? I have tried this:
System.out.println(test1.getLocation());
int oy = test1.getY();
int ox = test1.getX();
oy++;
ox++;
test1.setLocation(ox, oy);
validate();
test1.validate();
System.out.println(test1.getLocation());
The first location is the same as the last location. I know that you can’t change the location while in the layout normally, but how do you accomplish it? I have asked a similar question before and never got an answer. I have searched all over the internet for this, but I haven’t found an answer.
TL;DR – How do you move a component?
The problem is that the
LayoutManagerof the panel is setting the location of the label for you.What you need to do is set the layout to
nullby:This will make it so the frame/panel doesn’t try to layout the components by itself.
Then call
setBounds(Rectangle rect)on the label. Like so:lbl.setBounds(new Rectangle(new Point(200, 300), lbl.getPreferedSize()));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 is usually a better idea to use
LayoutManagers to work in your favour.Here is a great tutorial on getting started with using
LayoutManagers, if though you must use absolute then have a look at this tutorial