I am working on a fairly basic program, and at one point in my code (in a class extending JPanel), I tell the program to add a few components, followed by the repaint() command, but whenever I run the program, it doesn't repaint until I resize the window. I am running Java SE6 through JGrasp version 1.8.6_10 on Ubuntu 8.04 if it helps. A little bit later in my program, I remove these components, add a JLabel, and repaint() again. This time, it hides the components, but doesn't show the new JLabel. Finally, I tried repeating the function that adds the components (after removing them), and this time, It showed four of the six of them. The only two that didn't appear this time are the two that were redefined since the previous repaint() command. I have repeatedly checked to make sure that this was consistent, and it is. I'm sure this isn't that tough of a problem, but I am fairly new to Java. This school year, I am taking AP Computer Science, which was my first introduction to Java (I have been programming for over half my life, though, so that is not new to me).
Any help would be greatly appreciated,
do you call revalidate() on the panel accepting the changes?
Often when adding components a call to revalidate is all that is needed as this tells the JComponent's layout managers to layout the new components. Sometimes and in particular if you are removing components you have to call revalidate and then repaint.
I wonder though if what you really want to do is to swap components or JPanels with a CardLayout?
This worked perfectly!! Thank you so much :D I have read through my entire Java book, but never heard of the function revalidate(). Even though it is not necessary for all repaint() calls, I added it to all of them, if for no other reason to establish a habit :D
Again, it's only necessary when you need to have the layout managers re-layout the components. If you are doing pure drawing and not changing components, then there's no need to call it.
Glad it helped.
Don't establish bad habits :)
You need to call revalidate() after adding any components to a visible container. Append a call to repaint() only if any visual artefacts are seen.
And always call revalidate() + repaint() after removing any component from a visible container.
Superfluous code is not good programming.
edit Posts crossed. Morning/Evening, Fu.
Actually, whenever I was removing a component, I didn't need to call revalidate(), so rather than try to figure out where I need it an where I don't, I think ill be safe and always use it :D