- 论坛徽章:
- 0
|
找了3个Bug:
1:图像闪烁,原因在于没有重载update()函数,并且,在此函数内部只调用paint()函数
2:存放瞬间量的数组越界,原因在于TimeAndMoment内部的Vector是一个static变量,多个对象将共用一份变量
3:取得Map中的Vector出现空指针异常,原因在于存入和取出的key的类型不一样(这种低级错误!)
最后贴一个闪现了双层缓冲区的代码:
import java.awt.*;
import java.awt.event.*;
import java.awt.Canvas;
class ShowCanvas
extends Canvas {
Graphics offgc1, offgc2;
Image offscreen1 = null, offscreen2 = null;
boolean flag = true;
int X, Y;
int width, height;
public void update(Graphics g) {
// transfer offscreen to window
paint(g);
}
public void paint(Graphics g) {
if (offscreen1 == null) {
offscreen1 = createImage(width, height);
offgc1 = offscreen1.getGraphics();
}
if (offscreen2 == null) {
offscreen2 = createImage(width, height);
offgc2 = offscreen2.getGraphics();
}
if(flag){
draw_tendency();
}
g.drawImage(offscreen2, 0, 0, this);
g.drawString("*********************",100,100);
}
public void draw_tendency() {
// clear the exposed area
offgc1.setColor(Color.black);
offgc1.fillRect(0, 0, width,height);
offgc1.setColor(Color.green);
offgc1.drawString("draw tendency here!",width/2,height/2);
System.out.println("draw_tendency!");
// do normal redraw
//paint(offgc1);
flag = false;
}
public ShowCanvas() {
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.addMouseMotionListener(new ShowCanvas_this_mouseMotionAdapter(this));
this.setSize(new Dimension(400, 300));
this.width = 400;
this.height = 300;
}
void this_mouseDragged(MouseEvent e) {
X = e.getX();
Y = e.getY();
offgc2.clearRect(0,0,width,height);
offgc2.drawImage(offscreen1, 0, 0, this);
offgc2.setColor(Color.red);
offgc2.drawLine(X, height, X, 0);
offgc2.drawString(String.valueOf(X), X, 10);
repaint();
}
}
class ShowCanvas_this_mouseMotionAdapter
extends java.awt.event.MouseMotionAdapter {
ShowCanvas adaptee;
ShowCanvas_this_mouseMotionAdapter(ShowCanvas adaptee) {
this.adaptee = adaptee;
}
public void mouseDragged(MouseEvent e) {
adaptee.this_mouseDragged(e);
}
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/15642/showart_166342.html |
|