paint() and repaint() in Java

Daniel picture Daniel · May 26, 2012 · Viewed 123.8k times · Source

I've spent maybe the last two hours browsing and reading up on these methods and the Graphics class, and maybe I'm stupid, haha, but I'm just not understanding them. What are they for? I understand that they're supposed redraw or update components on the screen, but I have never understood why this is required (I'm new to this). For example, if I'm moving a JLabel around the screen, a call to setLocation() moves it just fine. Is that a scenario in which repaint() isn't required? In which scenarios is it useful, and why?

Apologies if you feel that this is a question that could be solved using the search function, but for whatever reason I'm not getting it.

Answer

Siva Charan picture Siva Charan · May 26, 2012

Difference between Paint() and Repaint() method

Paint():

This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.

Repaint():

This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.