15

When dealing with swing components, and when changing the components during runtime, one (often) needs to call the revalidate() method on the components in order for them to refresh.

What are the rules that determine whether or not one needs to revalidate a component? Does swing automatically call revalidate() when some certain properties on a component changes, and for some other properties not?

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
Datoraki
  • 1,223
  • 13
  • 26
  • See here http://stackoverflow.com/questions/1097366/java-swing-revalidate-vs-repaint – Romain Hippeau Apr 24 '11 at 10:00
  • @Romain already read, and not the same question. But thanks – Datoraki Apr 24 '11 at 10:15
  • hard to talk something because there is EDT, basically if you add/remove new JComponent, then you have to call revalidate()+ repaint(), if you change already visible JComponent, then validate() + repaint (my view revalidate covered validate too) – mKorbel Apr 24 '11 at 10:32

1 Answers1

11

The basic rule is: never - swing internals will take care of it. The basic exception to the rule is adding/removing components at runtime or changes which effect layout in ways the system can't know or for some reason doesn't want to react to.

While the exception is not very clearcut, it's infrequency in "normal" application development is: if there's a need to "often" call it there's a high probability something wrong with the code, f.i. a custom model implementation not notifying its listeners.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • Good answer, thanks =). Also, from the invalidate() javadoc: "This method will automatically be called on this component when a property value changes such that size, location, or internal layout of this component has been affected. This automatic updating differs from the AWT because programs generally no longer need to invoke validate to get the contents of the GUI to update. " – Datoraki Apr 24 '11 at 11:03
  • A refinement on the basic rule above: if you are adding children call revalidate to let the mixing code reset internal state. – BillYork67 Apr 05 '13 at 17:29