I'm making a painting program with Canvas, everything's fine except when I draw, the image starts to blink. I tried to set tm for the repaint method but this didn't fix the problem.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
public class Paint extends Canvas implements MouseListener, MouseMotionListener
{
private ArrayList rectrangles = new ArrayList();
private ArrayList circles = new ArrayList();
private ArrayList shapes = new ArrayList();
private Color color;
private int strk_width;
private Path2D shape;
private boolean m_alzada = true, rectangle=false, circle = false;
private int uX,uY,x,y;
public Paint(){
this.color = Color.black;
this.setBackground(Color.white);
this.shape = new Path2D.Float();
this.shape.moveTo(0,0);
this.strk_width = 5;
}
@Override
public void paint(Graphics g){
super.paint(g);
Graphics2D d = (Graphics2D) g;
d.setColor(Color.white);
d.fillRect(0,0,this.getWidth(), this.getHeight());
d.setStroke(new BasicStroke(this.strk_width));
d.setColor(color.black);
d.draw(this.shape);
}
public void update(Graphics g){
paint(g);
}
@Override
public void mouseClicked(MouseEvent e){}
@Override
public void mouseReleased(MouseEvent e){
this.lastx = e.getX();
this.lasty = e.getY();
}
@Override
public void mouseExited(MouseEvent e){}
@Override
public void mouseEntered(MouseEvent e){}
@Override
public void mousePressed(MouseEvent e){}
@Override
public void mouseDragged(MouseEvent e){
this.x = e.getX();
this.y = e.getY();
this.shape.lineTo(x,y);
repaint();
}
@Override
public void mouseMoved(MouseEvent e){}
}
import javax.swing.*;
import java.awt.event.*;
public class Main extends JFrame
{
public Paint dibujo;
public Main(){
dibujo = new Paint();
dibujo.addMouseMotionListener(new MouseMotionListener(){
@Override
public void mouseDragged(MouseEvent e){
dibujo.mouseDragged(e);
}
@Override
public void mouseMoved(MouseEvent e){
dibujo.mouseMoved(e);
}
});
JPanel p = new JPanel();
p.add(dibujo);
dibujo.setBounds(20,40,600,400);
add(p);
}
@SuppressWarnings("unchecked")
public static void main(String[] args){
Main m = new Main();
m.setVisible(true);
m.setSize(700,700);
}
}
Any help would be appreciated
I just fixed it with double buffering