This week's giveaway is in the Threads forum.
We're giving away four copies of Java Concurrency Live Lessons and have Doug Schmidt on-line!
See this thread for details.
Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JLabel visible only when resizing  RSS feed

 
Diego Klappenbach
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I'm just starting out with Swing but I didn't expect to run into problems so soon...
As far as I can understand, this code should show a string (the JLabel) in the middle of the frame. Well, it does, but not at once, only when I resize the window. After the first resizing, the string stays visible all the time.
Here's the code:

The same behavior appears when using a JButton, or when I pass an ImageIcon to the JLabel. All these things show up in the middle of the frame (at the top), but only after resizing the window.
Why don't they appear as soon as the window is created?
Thanks for your help!
Regards,
Diego
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Normally you assemble the window and then call setVisible(true). If you call setVisible() first, then the layout manager won't actually lay out the components until you call validate() on the container (or do something else that triggers layout, like resizing the window.)
So either move the setVisible() call until after the add(jl) call, or call jframe.validate() after it.
 
Diego Klappenbach
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest,
this solved the problem.
Just out of curiosity:
you say "normally" one should put setVisible( true ) at the end. What do you mean by that?
I'm asking because running the same code on a Linux machine didn't cause this behavior, while it did appear on my W2K machine, as well as on a XP one.
 
Jason Steele
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well in your case, you set the frame visible and then changed the layout. That would need a call to update() to update the graphics.
 
Brian Pipa
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On a related note, I have a Swing app that comes with an empty table then I do some disk access and fill in the table but the data doesn't show up in the table til I resize. Sounds like the same problem?
brian
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!