Redrawing and Double Buffer confusion

First post O_O

This has probably been asked a million times before, but I did a little search and couldn’t find a solution to my problem.

Anyway, I’ve made a window with a rectangle that redraws itself vertically until the user clicks somewhere else in the window and it starts again from that position. Problem is I only want one rectangle to show at a time, ie I want to erase the previous ones.

I thought I’d try double buffering, but I can’t get my head round it. Would I need to use BufferedStrategy or BufferedImage? How do I draw offscreen?

Confusing thing is, I made a program about half a year ago that does exactly what I want this to do, only I’ve used paintComponent and Ellipse2D instead of paint and drawRect. Does it matter which one I use?

Sorry if I’m not making any sense, I’m not very good at forum-posting :stuck_out_tongue:

Thanks in advance for any help!

Do you call super.paint(g) in your overwritten paint method? This would cause the update method to get called to blank out the screen.
You could instead manually do this by either using Graphics2D.fillRect to fill in the whole screen or just the area you want cleared(dirty rectangles).

To draw off screen create a BufferedImage and use the createGraphics() function to get the images Graphics2D object then draw like normal to the image, when your ready to display it you draw the image using the components graphics object supplied by the paint function.

I’m thinking zoto is right, although he means super.paintComponent(g) rather than paint (because that’s what it appears you’ve used).

I’ve used the fillRect approach he mentions as well, and if you’re only drawing one or two things and you are rendering to a large area (if the size of your Canvas is large) then it is definitely a better option not to call super.paintComponent, as it’s really rather slow except in smaller windows.

Thanks a lot guys! I’d used super.paintComponent instead of super.paint, which was causing the problem! Is there any point of ever using super.paintComponent(g) then?

It paints the background-color, if the component is opaque.

It also draws the border, if you have one set