Reputation: 1136
I am playing around with the Java graphics class a little bit and I was just wondering--when is it necessary to call the method repaint()
? I tried commenting it out and it didn't seem to affect my output GUI. I've seen it used a lot in Java GUI code that I've read, though. Would anyone mind explaining when to use it and when not to use it?
Upvotes: 5
Views: 39134
Reputation: 1066
The only stuff I can think of:
new Thread() {
@Override
public void run() {
while (ClassName.this.isVisible()) {
ClassName.this.updateStatusLabel();
ClassName.this.validate();
ClassName.this.repaint(50L);
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
Log.log(e);
}
}
}
}.start();
Suppose you have the above code in the constructor of a JDialog. What updateStatusLabel does is checking a boolean variable, either public or settable through a method, and set the icon of a JLabel in base to such boolean. If you don't validate and repaint the GUI, the modification won't be shown until another event, most likely an user-triggered one, is thrown. And, if the user is waiting for the label to show a certain icon because of, let's say, it indicated if a device is reachable through the Internet, he/she'll never interact (or, at least, you're delaying interactions so much).
Upvotes: 0
Reputation: 3107
It's never really necessary in most swing applications, because they handle it automatically (for common operations such as changing text values on buttons and adding data to a list box).
Generally, it's only if you've made some sort of change that swing won't automatically pick up - for example, you're not using a layout manager and are resizing components manually (because normally the layout manager repaints its components when necessary).
Upvotes: 1
Reputation: 877
The repaint()
refreshes the view (component), so whenever you make any change on the component, you must call it. For instance, if you rotate the graphical component, you must make a call to repaint()
in order to see the change on the containing component
Upvotes: 1
Reputation: 1444
When you launch your application, you "paint" your GUI.
You need to call repaint()
when you want to re-draw your GUI because you have changed something inside.
If you want to delete a button, you need to remove it (or make it invisible) then you need to call validate()
or repaint()
to re-calculate (re-draw) the GUI.
Upvotes: 0