Is using (in the paint method) g.clearRect() the correct way to clear the screen? It's working but I don't know if there is a better way. . google says it is supposed to clear automatically when update is called but that doesn't seem to happen.

Recommended Answers

All 6 Replies

If you consider that the component generally starts with a cleared surface of the background color, it's often unnecessary to use clearRect() or fillRect() to clear out the background, but if you are maintaining an image reference for purposes of buffering some updates then you would need to clear that manually before painting the new data.

If you consider that the component generally starts with a cleared surface of the background color, it's often. .

True, it did start out like that, but what is the relevance of that? I'm just moving rectangles around, but when I move the rectangle, the old ones were duplicating because the old ones never got 'erased'. I fixed that problem by using clearRect

True, it did start out like that, but what is the relevance of that? I'm just moving rectangles around, but when I move the rectangle, the old ones were duplicating because the old ones never got 'erased'. I fixed that problem by using clearRect

I generally have a class that extends JPanel and I repaint everything anytime anything changes, so if I have ten rectangles and I'm dragging one, I have the paintComponent function paint all ten rectangles every time. At the top of paintComponent, I make a call to the super-class's (JPanel) paintComponent function and that completely clears everything. If you have a lot of things that need to be painted, it may not be the most efficient way of doing things from a processing power point of view, but from a coding point of view, it's the easy, surefire way of doing things in my experience as you never have to remember to "clear" anything.

Yes, sorry, I guess I wasn't very clear. I had a scenario like what Vernon mentions above in mind when I said that the component starts with a cleared background. I was assuming a call to super.paintComponent() before any other painting.

Ok, I got you now. I demonstrated my project earlier today and everything worked perfectly, btw. But I just implemented what you said and it works also, so it's probably preferable considering it's only one line of code & that's the standard.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.