4

I'm making an app which contains a java.awt.Canvas to display a sequence of conected nodes like in a graph. while editing, the last dot is conected to the mouse cursor with a java.awt.geom.Line2D so that it must be repainted everytime the user moves the mouse, and it causes a really disgusting -flashy- effect on screen.

I did this once before, and I know the solution was so easy and didn't need a really hard code, but to mess around with paint(g), repaint(g) and update(g) methods, despite it, I cannot manage to solve it and hope someone can help me!

Lots of thanks in advance!! :)

Dane411
  • 823
  • 1
  • 13
  • 27
  • Look at the Java API java.awt.Canvas class. 'A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.' – DaveJohnston Nov 17 '10 at 11:51

2 Answers2

5

You need to do Double Buffering to get rid of the flickering. Loads of examples if you google for it.

Found a previous question that has more info. Here is another example.

Community
  • 1
  • 1
willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
  • Thank you Erik, I've already thought about double buffering, but I was sure there was an even easier option, most surely I had found over the net, but now I can't remember (the fact is that i programmed this once before, but I lost the only copy since I didn't backed it up) :( – Dane411 Nov 17 '10 at 13:10
  • I saw in the accepted answer, in the link you gave me this piece of code: public void update(Graphics g) { // override this because the default implementation always // calls clearRect first, causing unwanted flicker paint(g); } Which based on the comments seems to be the solution I took the first time, but now doesn't seem to work, since I keep seeing those flashes What could have happened it not to work this time? – Dane411 Nov 17 '10 at 13:27
  • @Dane411 - I have not actually done any double buffering since 1998 for a university course, but it really should be very straightfoward. Try the other example or google it. If you cannot get it to work post the code and maybe someone can help you – willcodejavaforfood Nov 17 '10 at 14:38
1

Here is a tutorial on double buffering http://download.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html

The idea is basically that you draw to an offscreen image, then once you are finished drawing the entire image you paint that image to the screen.

DaveJohnston
  • 10,031
  • 10
  • 54
  • 83
  • Nice lesson, but BufferStrategy didn't work for me, some kind of Exception, anyway I fixed the flickering with a BufferedImage :) – Dane411 Nov 17 '10 at 21:09