java - 创建基本绘图程序

标签 java bufferedimage

我正在尝试创建一个简单的绘图程序,在单击按钮时保存基本绘图。我从课本上复制了绘制方法,我只是在玩弄。这是我创建的缓冲图像:

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/

相关文章:

java - 如何使用 Solr/Lucene 序列化/反序列化 map ?

java - Parsing_Exception [match] 查询不支持 [auto_generate_synonyms_phrase_query]

java - 如何使用剪辑来减少绘画时间?

JavaFX:将像素写入 PixelWriter 的最快方法

javafx调整图像大小的内存消耗提示

java - Hibernate AbstractBatchImpl sql 必须为非空

JAVA - 如何通过比较列表中的多个值来使用比较器对对象列表进行排序

java - 使用 Apache Http Client 4.5.3 从 jdk1.6.0_45 向 API 网关发出简单的 POST 请求

java - BufferedImage 可以写入任何格式的文件吗?

Java-将缓冲图像转换为字节[]而不写入磁盘