2013-10-17 35 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

相關問題