尝试使用awt canvas上的鼠标来绘制图形(目前为线)。Iam首次尝试Java图形。所以不确定如何去做。这是我的第一次尝试:
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();
// comp.repaint(); << for cleaning up the intermediate lines : doesnt work :(
g.drawLine(sx, sy, x, y);
return;
}
onDrag = true;
sx = e.getX();
sy = e.getY();
System.out.println("Draggg");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("Released");
if (onDrag)
onDrag = false;
}
}
public class Can extends Canvas {
@Override
public void paint(Graphics g) {
}
}
}
问题:1)将窗口最小化并还原后,绘制的线条消失了(由于要重新绘制)2)我要的是该线条应跟随鼠标移动(拖动时)。最后一行应该从按下位置到释放鼠标的位置。现在请礼节,当鼠标移动时,将绘制新的线条。我不确定如何清除画布上的中间线。
有人可以帮我解决这些问题吗?