Reputation: 4335
We override paint method like this
public void paint(Graphics g)
{
g.drawString(msg,xpos,ypos);
}
If we have another method lets say a mousepressed event method
public void mousePressed(MouseEvent me)
{
xpos=me.getX(); // msg, xpos and ypos are variables of class
ypos= me.getY();
msg="You pressed mouse";
repaint();
}
Why cant we call paint(Graphics g)
rather than repaint()
?
Upvotes: 3
Views: 2913
Reputation: 3753
Calling repaint() doesn't necessarily immediately cause a call to paint(). It requests that a call be scheduled.
You should generally call repaint rather than paint so that the GUI framework can properly schedule the repainting. It will do things like make sure paint gets called on the right thread, and has a chance to merge multiple calls to repaint if they happen before the framework gets around to doing the actual painting.
Calling repaint will be much more robust.
Upvotes: 9
Reputation: 88408
You should probably try that. You will notice
Graphics
object g
somehow.paint
in the body of an event handler is not a best practice because it causes the body of that method to execute on the GUI thread right away, so no more events can be processed until paint
returns. OTOH, repaint
schedules a paint event to occur at some convenient point in the future and does not make the GUI appear to hang. Granted, in your case, drawString
isn't terribly slow, but in general....Here is the classic article on painting, from the Java people themselves.
Upvotes: 14