我正在尝试创建一个简单的绘图程序,在按钮点击时保存基本图形。我从我的教科书中复制了绘制方法,我只是在玩弄。这是我创建的缓冲图像:
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文件只是黑色。
答案 0 :(得分: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);
}