改进后的代码如下:
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
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 GraphicsDemo {
public static void main(String[] args) {
new FrameFF("draw....");
}
}
class FrameFF extends Frame {
//frame大小
private static final int AREA_LENGTH = 500 ;
//记录先前位置。置为-1的原因请见MouseMotionListener
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();
FrameFF(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();
//看你原先的代码还需要得到事件源,其实没有必要,因为是Frame
//的内部,所以其属性是可以访问的,直接调用其方法即可
repaint();
}
});
//窗口关闭
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void paint(Graphics g) {
//整体绘制,免去每次集合遍历时间和重新绘制所有点时间。应该会剩下不少时间的,虽然感觉不到,呵呵
g.drawImage(image,0,0,null);
}
}
希望可以帮到你 |