在线程中绘制BufferedImage

时间:2014-11-13 23:47:55

标签: java multithreading canvas bufferedimage

我试图从线程中绘制BufferedImage,然后在画布上显示所述图像。 当我从Canvas的paintComponent方法中改变BufferedImage时,一切正常,但是当我尝试从正在运行的线程中改变它时 - 没有任何反应。

换句话说;如果我将Graphics2D代码从线程复制到paintComponent方法,一切正常。

我的代码片段(某些变量/值是临时的):

class DrawThread implements Runnable
{
    @Override
    public void run()
    {
        while(true)
        {
            Graphics2D g2d = canvas.getImage().createGraphics(); 

            g2d.setColor(Color.GREEN);

            Rectangle rect2 = new Rectangle(10, 0, 20, 20);

            g2d.draw(rect2);
            g2d.dispose();

            try
            {
                Thread.sleep(100);
            } 
            catch (InterruptedException e) 
            {
                e.printStackTrace();
            }
        }
    }
}

class RectangleCanvas extends Canvas 
{
    public BufferedImage image;

    public RectangleCanvas() 
    {
        this.setPreferredSize(new Dimension(280, 280));
        image = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
    }

    public synchronized BufferedImage getImage()
    {
        return this.image;
    }

    @Override
    protected void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        g.drawImage(getImage(), 0, 0, this);
    }
}

0 个答案:

没有答案