4

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?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Coupon22
  • 395
  • 8
  • 24
  • 1
    Swing gives each component `BorderLayout` as a default layout manager. Try turning it off for the panel with `setLayoutManager(null)` to enable absolute positioning. – millimoose Sep 07 '12 at 22:00
  • 3
    @millimoose: No, the default layout of `JFrame` is `BorderLayout`; the default layout of `JPanel` is `FlowLayout`; absolute positioning is _not_ required. – trashgod Sep 07 '12 at 22:10
  • See also this [example](http://stackoverflow.com/a/2562685/230513) and [variation](http://stackoverflow.com/a/2563350/230513). – trashgod Sep 07 '12 at 22:10

3 Answers3

3

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

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
3

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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
2

The setLocation() method works when setting the layout to null. If you are using a layout manager then one choice would be that you remove the component from its container and add it back using the new layout constraints.

Dan D.
  • 32,246
  • 5
  • 63
  • 79