2013-10-17 33 views
0

我想创建一个简单的绘图程序,在按钮单击时保存一个基本绘图。我从我的教科书中复制了绘画方法,我只是在附近玩耍。这是缓冲的图像我已经建立:创建一个基本绘图程序

private static BufferedImage bi = new BufferedImage(500, 500, 
     BufferedImage.TYPE_INT_RGB); 

,这将创建的烤漆面板:

public PaintPanel() { 

    addMouseMotionListener(

    new MouseMotionAdapter() { 
     public void mouseDragged(MouseEvent event) { 
      if (pointCount < points.length) { 
       points[pointCount] = event.getPoint(); 
       ++pointCount; 
       repaint(); 
      } 
     } 
    }); 
} 

public void paintComponent(Graphics g) { 

    super.paintComponent(g); 

    for (int i = 0; i < pointCount; i++) 
     g.fillOval(points[i].x, points[i].y, 4, 4); 
} 

点击一个按钮:

save.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      PaintPanel.saveImage(); 
      System.exit(0); 
     } 

我调用这个方法:

public static void saveImage() { 

    try { 
     ImageIO.write(bi, "png", new File("test.png")); 
    } catch (IOException ioe) { 
     System.out.println("Eek"); 
     ioe.printStackTrace(); 
    } 

} 

但是png文件t我保存的帽子只是黑色。

回答

2

BufferedImage和面板组件有2个不同的Graphics对象。因此,有必要明确地更新前者的Graphics对象:

Graphics graphics = bi.getGraphics(); 
for (int i = 0; i < pointCount; i++) { 
    graphics.fillOval(points[i].x, points[i].y, 4, 4); 
} 
+0

谢谢你,我想我忘记了需要更新缓冲图片,我以为他们是同一个。谢谢!! – Sam

相关问题