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() ?
You should probably try that. You will notice
Graphicsobjectgsomehow.paintin 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 untilpaintreturns. OTOH,repaintschedules 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,drawStringisn’t terribly slow, but in general….Here is the classic article on painting, from the Java people themselves.