Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

paint() and repaint() in Java

Tags:

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.

like image 936
Daniel Avatar asked May 26 '12 18:05

Daniel


People also ask

What is the difference between paint () and repaint () in Java?

The repaint() method, which can't be overridden, is more specific: it controls the update() to paint() process. You should call this method if you want a component to repaint itself or to change its look (but not the size).

What does repaint (); do in Java?

repaint(): The repaint() is intended to allow various methods to call for a re-rendering of the component. No graphics context is needed for repaint(). A call to repaint() calls update().

What is paint () method?

The method paint() gives us access to an object of type Graphics class. Using the object of the Graphics class, we can call the drawString() method of the Graphics class to write a text message in the applet window.

When should we use repaint method?

The repaint() Method in Java This method is used to call the update() method internally that calls the paint() method to repaint the component. The paint() and repaint() both are used to paint a component, but the repaint() method internally calls paint() to paint the component. We cannot override the repaint() method.


Video Answer


1 Answers

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.

like image 188
Siva Charan Avatar answered Sep 23 '22 03:09

Siva Charan