Trying to enable figure drawing (line at the moment) with the mouse on awt canvas. First I test java graphics. Therefore, I’m not sure how to do it. This is my first attempt:
package def.grafi; import java.awt.Canvas; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Dra { Frame f = new Frame(); public void disp() { f.setBounds(100, 100, 200, 200); MosL ml = new MosL(); Can c = new Can(); f.add(c); c.addMouseListener(ml); c.addMouseMotionListener(ml); f.setVisible(true); } public static void main(String[] args) { Dra d = new Dra(); d.disp(); } public class MosL extends MouseAdapter { int sx = 0; int sy = 0; boolean onDrag = false; @Override public void mouseDragged(MouseEvent e) { if (onDrag) { int x = e.getX(); int y = e.getY(); Canvas comp = (Canvas) e.getSource(); Graphics g = comp.getGraphics();
Problems: 1) When the windows are minimized and restored, the drawn line is gone (due to repainting) 2) I want the line to follow the mouse (when it is being dragged). the end line should extend from the point of click to the point of release of the mouse. Rite now, when the mouse moves, new lines appear. I am not sure how to clear the intermediate lines from the canvas.
Can someone help me solve these problems?
source share