3

I'm just doing my personal project that draws a basic map using Swing.

I have many issues but the worst one is that the position of JLables changes every time I

  1. Resize the frame
  2. Set them invisible and visible again (setvisible(false)->setvisible(true))
  3. Move the screen to another tab 'Map 2' and come back to Map 1 (The frame has JTabbedPane)

It's sad that I don't have enough reputation to upload images :(

all the JLables are located on the top of the JPanel.

It's like

Before
.-----------------------------------------------
.-----------------------------------------------
.---------Label1-----------------------------
.-----------------------------------------------
.------------------Label2--------------------
.-----------------------------------------------
.-------------------------------Label3-------
.-----------------------------------------------
.-----------------------------------------------
.-----------------------------------------------

After
.-----------------------------------------------
.---------Label1 Label2 Label3-----------
.-----------------------------------------------
.-----------------------------------------------
.-----------------------------------------------
.-----------------------------------------------
.-----------------------------------------------
.-----------------------------------------------
.-----------------------------------------------
.-----------------------------------------------

I also tried using setLocation(new Point(x,y)); after resizing happens but nothing came out.

Any tips will be appreciated. :) enter image description here enter image description here

Eugene Yu
  • 3,708
  • 4
  • 21
  • 27
  • Post your source, please – Aubin Oct 16 '12 at 19:21
  • 2
    @DavidKroukamp Thanks David I'll keep the post in mind for future questions and this one! But the panel that contains those Labels does not use LayoutManager. So the Labels are located using 'setLocation'. So setLocation for the first time works but not for later :( – Eugene Yu Oct 16 '12 at 19:24
  • +1 for ACSII art; an [sscce](http://sscce.org/) is always welcome, and a [picture](http://meta.stackexchange.com/questions/99734/how-do-i-create-a-screenshot-to-illustrate-a-post) is worth _n_ words. :-) – trashgod Oct 16 '12 at 19:31

1 Answers1

7

You have used absolute positioning without setting the layout accordingly. Refreshing the display in the presence of FlowLayout, the default for JPanel, causes the layout you see in after. Using setLayout(null) may work, but the preferred approach is to use the intended layout manager.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • I edited Images for other viewers. And the reason why I didn't use layout manager is to locate Labels anywhere on the panel. – Eugene Yu Oct 16 '12 at 19:31
  • 1
    Good use case for absolute positioning; also consider [tooltips](http://stackoverflow.com/a/5957412/230513). – trashgod Oct 16 '12 at 19:35