Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move a component in a layout?

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?

like image 624
Coupon22 Avatar asked Feb 19 '23 05:02

Coupon22


2 Answers

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 by:

setLayout(null);

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

like image 169
David Kroukamp Avatar answered Mar 04 '23 03:03

David Kroukamp


may to help you to look at DragLayout and to combine with ComponentMover, made by @camickr

like image 40
mKorbel Avatar answered Mar 04 '23 05:03

mKorbel