我一直在尝试制作一个简单的程序,它有一个类似画笔的工具,当打开它时创建了一个 JFrame 并在其中放置了一个 Canvas 用户可以绘制的地方。现在,我正在尝试使用在退出时调用的 saveCanvas 方法保存绘图,但无论我做什么,我都会得到一个黑色图像。这是我的代码:
public class Test{
JFrame f;
Canvas c;
int x=-1, y=-1;
public Test() {
f = new JFrame();
f.setSize(1200, 800);
c = new Canvas(){
@Override
public void paint(Graphics g){
super.paint(g);
}
};
f.add(c);
c.addMouseMotionListener(new MouseMotionListener(){
@Override
public void mouseMoved(MouseEvent e) {
// empty
}
@Override
public void mouseDragged(MouseEvent e){
if(x==-1){
x = e.getX();
y = e.getY();
}
c.getGraphics().fillOval(x, y, 5, 5);
x = e.getX();
y = e.getY();
}
});
f.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent evt) {
onExit();
}
public void onExit()
{
saveCanvas(c);
System.exit(0);
}
});
f.setVisible(true);
}
public static void main(String[] args) {
Test paintBrush = new Test();
}
public static void saveCanvas(Canvas canvas){
BufferedImage image=new BufferedImage(canvas.getWidth(), canvas.getHeight(),BufferedImage.TYPE_INT_ARGB);
Graphics2D g2=(Graphics2D)image.getGraphics();
boolean x = false;
while(!x){
x = g2.drawImage(image, 0, 0, null);
}
try
{
ImageIO.write(image, "png", new File("C:\\test\\canvas.png"));
}
catch (Exception e) {
}
}
}
关于可能导致这种情况的任何想法?