I use Java awt. When redrawing, flicker appears. Tried to do double buffering, but all the flicker remained exactly.

public class SignatureCanvas extends Canvas{ private ArrayList<Point> points = new ArrayList<Point>(); private Image buffer = null; private void cleanPoints() { points.clear(); } public SignatureCanvas() { super(); this.addMouseMotionListener(new SigCanvasMouseMotionListener(this)); this.addMouseListener(new SigCanvasMouseListener(this)); System.out.println(isDoubleBuffered()); } @Override public void paint(Graphics g) { buffer = createImage(this.getWidth(), this.getHeight()); Graphics gBuf = buffer.getGraphics(); gBuf.setColor(Color.WHITE); gBuf.fillRect(0, 0, this.getWidth(), this.getHeight()); gBuf.setColor(Color.BLACK); for(int i = 0; i < points.size() - 1; i++) { Point p1 = points.get(i); Point p2 = points.get(i); gBuf.drawLine((int)p1.getX(), (int)p1.getY(), (int)p2.getX(), (int)p2.getY()); } g.drawImage(buffer, 0, 0, null); } public void mouseDragged(MouseEvent e) { Point tmp = new Point(e.getX(), e.getY()); points.add(tmp); this.repaint(); } public void mouseReleased(MouseEvent e) { }} class SigCanvasMouseListener implements MouseListener{ private SignatureCanvas canvas; public SigCanvasMouseListener(SignatureCanvas c) { canvas = c; } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e){ canvas.mouseReleased(e); } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { }} class SigCanvasMouseMotionListener implements MouseMotionListener{ private SignatureCanvas canvas; public SigCanvasMouseMotionListener(SignatureCanvas c) { canvas = c; } @Override public void mouseDragged(MouseEvent e) { canvas.mouseDragged(e); } @Override public void mouseMoved(MouseEvent e) { }} 

Tell me, please, what could be the problem?

  • one
    sorry for oftop, but then I asked a similar question, and they advised me to throw awt and use swing - arg
  • I solved the problem if the answer in the comment to my question is interesting. - nanotexnik

1 answer 1

Solved a problem.

In order to avoid flickering, you need to overload not paint(Graphics g) , but update(Graphics g) . I do not know what is the reason, maybe someone will explain? as in almost all articles on the Internet paint overloaded.

PS I use java 1.7.0

  • one
    Look, here they write something about the situations in which paint () and update () are called. I didn’t go deeply, but the impression is that paint () is called every time something can be drawn, and update (), when it’s impossible not to paint. - avp
  • one
    Thanks for the link. This is probably the answer to the question: "If you are not a lightweight component) and simply calls (). - nanotexnik