This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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?
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.
Joined: Feb 16, 2007
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?
Joined: Nov 13, 2002
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 ]