简体   繁体   English

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

[英]Simple bufferedimage flickering when calling repaint

I'm trying to create a webcam view with openCV but when I repaint the saved image it flickers and the images look half gray sometimes. 我正在尝试使用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();
    }
}

Don't read your image in your paintComponent() method. 不要在paintComponent()方法中读取图像。 Read the image in your constructor. 在构造函数中读取图像。

Also, don't call repaint() from your paintComponent() method. 另外,不要从paintComponent()方法中调用repaint()。 If you need to continuously redraw, use a Thread or a Timer. 如果需要连续重绘,请使用线程或计时器。

Edit: this might need some tweaking, but it's the basic approach I'm talking about: 编辑:这可能需要一些调整,但这是我正在谈论的基本方法:

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();
        }
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM