class MainCanvas extends Canvas implements Runnable, MouseListener {
Color rgbcolor;
int x;
int y;
int dx;
int dy;
Thread t;
BufferedImage bimage = new BufferedImage(300, 300, BufferedImage.TYPE_INT_RGB);
Graphics g2;
MainCanvas(){
setBackground(Color.WHITE);
addMouseListener(this);
t=new Thread(this, "mythread");
t.start();
}
public void paint(Graphics g){
g2 = bimage.createGraphics();
g2.drawImage(bimage, 0, 0, 30, 300, null);
g2.setColor(rgbcolor);
g2.drawLine(x, y, dx, dy);
g2.dispose();
}
public void update(Graphics g){
g2 = bimage.createGraphics();
g2.drawImage(bimage, 0, 0, 30, 300, null);
g2.setColor(rgbcolor);
g2.drawLine(x, y, dx, dy);
g2.dispose();
}
public void setRGBColor(Color rgbcolor){
this.rgbcolor=rgbcolor;
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
x=arg0.getX();
y=arg0.getY();
dx=arg0.getX();
dy=arg0.getY();
System.out.println("mouse pressed");
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
dx=arg0.getX();
dy=arg0.getY();
System.out.println("mouse released");
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.currentThread();
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
}
我不确定为什么它不能正常工作,我能做的最好就是在图像后面画画。我基本上只是试图绘制图像。我尝试了几种不同的方法,而不是g = bimage.getGraphics().setColor()
,但我知道有更好的方法。
答案 0 :(得分:0)
我正在绘制我的图像,但是之后没有将它画到画布上。我需要做的是用图形Graphics2D g2绘制到我的bufferedImage,然后使用Graphics g绘制/绘制图像。
Graphics2D g2 = bimage.createGraphics();
g2.setColor(rgbcolor);
g2.fillRect(x, y, dx, dy);
g2.dispose();
g.drawImage((Image)bimage,0,0,100,100,null);