• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

adding components outside initialization

 
Gotham Sewani
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I add a component to my applet,during the course of execution (that is,not inside the init() or the start() method,but,say,on clicking a button),then the component doesnt appear.In appletviewer,the component becomes visible only when I resize the window.
Why is this happening,and what can I do if I want the components to appear immediately?
 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I sometimes find it useful to invoke the container's "revalidate" and/or "repaint" methods (revalidate would be available for JComponents, e.g. if you add your components into a JPanel inside the JApplet, or if you know the JApplet's contentPane can be cast to JComponent).

Just in case, i'd also check that everything else is in order - components could also disappear due to not having enough area to display (on some layouts), badly written custom layout managers, misuse of threads, etc.
 
Gotham Sewani
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
That was exactly the problem.Calling validate() after adding the components worked like magic!
By the way,can you shed some light on why do we need to do that?
 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have often wondered myself.
The java 5 API does mention it explicity:

Container.add(Component):
...
If a component has been added to a container that has been displayed, validate must be called on that container to display the new component. If multiple components are being added, you can improve efficiency by calling validate only once, after all the components have been added.


Thus, it *might* involve performance: adding a component requires to re-calculate the container's layout and repaint, but perhaps they didn't want to build it inherently into 'add()' method because it's inefficient for 'bulk' adding. And until validation, they might have preferred to hide the container rather then show invalid info.

Note it's just a guess - I hope your post gets additional replies .
[ March 15, 2007: Message edited by: Sol Mam-Orn ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic