双缓冲的问题!

wuyan19831013 2006-09-06 03:20:34
做了个Canvas,打算生成两块内存,一层显示字符,另一层响应鼠标事件,但是,现在啥也显示不出来,如果要验证,请将此类放到JFrame中,代码如下:
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
}

public void paint(Graphics g) {

if (offscreen1 == null) {
offscreen1 = createImage(width, height);
offgc1 = offscreen1.getGraphics();
}
if (offscreen2 == null) {
offscreen2 = createImage(width, height);
offgc2 = offscreen1.getGraphics();
}
if(flag){
draw_tendency();
}
g.drawImage(offscreen2, 0, 0, this);
}

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);
}
}

请高手指点
...全文
154 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuyan19831013 2006-09-06
  • 打赏
  • 举报
回复
问题找到了

第一个来的给分
··

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧