调用重绘时,简单的bufferedimage闪烁

时间:2014-06-23 13:05:09

标签: java swing repaint flicker

我尝试使用openCV创建网络摄像头视图但是当我重新绘制保存的图像时,它会闪烁,图像看起来有时会变成灰色。

import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;

    public class Panel extends JPanel {

    BufferedImage img;
    public Panel() {
        super(true);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);


        try {
            img = ImageIO.read(new File("webcam.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        g.drawImage(img, 0, 0, 640, 480, this);
        repaint();
    }
}

1 个答案:

答案 0 :(得分:4)

不要在paintComponent()方法中读取图像。阅读构造函数中的图像。

另外,不要从paintComponent()方法调用repaint()。如果需要不断重绘,请使用线程或计时器。

编辑:这可能需要一些调整,但这是我所说的基本方法:

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class Panel extends JPanel implements Runnable{

BufferedImage img;
public Panel() {
    super(true);
    new Thread(this).start();
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if(img != null){
        synchronized(this){
            g.drawImage(img, 0, 0, 640, 480, this);
        }
    }
}

public void run(){
    while(true){
        try {
            synchronized(this){
                img = ImageIO.read(new File("webcam.jpg"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        repaint();

        try {
            Thread.sleep((long) (1000.0/30));
        } 
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
}