我之前做画图的时候,做出来的效果和你一样,后来请教了一下别人,改了一下,用画点的方式,不太好,因为不可能连起来,别人教我是用画直线的方法
下面是代码,你参考下吧
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
public class GraphicsDemo2 {
public static void main(String[] args) {
new FrameFFF("draw....");
}
}
class FrameFFF extends Frame {
//frame大小
private static final int AREA_LENGTH = 500;
private int preX = -1;
private int preY = -1;
//用做缓冲
private BufferedImage image = new BufferedImage(AREA_LENGTH, AREA_LENGTH,
BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
FrameFFF(String name) {
super(name);
setBounds(300, 150, AREA_LENGTH, AREA_LENGTH);
setVisible(true);
//将底色置为白色,便于观看
g.fillRect(0, 0, AREA_LENGTH, AREA_LENGTH);
//添加鼠标监听
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
//均大于0时肯定已经在内部了,且已经点击过一次,记录下了第一次的坐标
//所以这时划线已经没有问题了
if (preX > 0 && preY > 0) {
g.setColor(new Color(123, 44, 82));
g.drawLine(preX, preY, e.getX(), e.getY());
}
preX = e.getX();
preY = e.getY();
repaint();
}
});
//窗口关闭
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
preX = -1;
preY = -1;
}
});
}
public void paint(Graphics g) {
// 整体绘制
g.drawImage(image, 0, 0, null);
}
}
希望可以帮到你 |