Reputation: 93
I am trying to create a simple draw program that saves a basic drawing upon button click. I copied the draw methods from my textbook, I am just toying around. This is the buffered image I have created:
private static BufferedImage bi = new BufferedImage(500, 500,
BufferedImage.TYPE_INT_RGB);
And this creates the paint panel:
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);
}
On a button click:
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PaintPanel.saveImage();
System.exit(0);
}
I call this method:
public static void saveImage() {
try {
ImageIO.write(bi, "png", new File("test.png"));
} catch (IOException ioe) {
System.out.println("Eek");
ioe.printStackTrace();
}
}
But the png file that I save is just black.
Upvotes: 0
Views: 105
Reputation: 159754
The BufferedImage
and panel component have 2 distinct Graphics
objects. Therefore it is necessary to explicitly update the Graphics
object for the former:
Graphics graphics = bi.getGraphics();
for (int i = 0; i < pointCount; i++) {
graphics.fillOval(points[i].x, points[i].y, 4, 4);
}
Upvotes: 2