我正在尝试创建一个简单的绘图程序,在单击按钮时保存基本绘图。我从课本上复制了绘制方法,我只是在玩弄。这是我创建的缓冲图像:
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 文件只是黑色。
最佳答案
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);
}
关于java - 创建基本绘图程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19436514/