Sunday, 15 February 2015

java - Simple bufferedimage flickering when calling repaint -



java - Simple bufferedimage flickering when calling repaint -

i'm trying create webcam view opencv when repaint saved image flickers , images half grayness sometimes.

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); seek { img = imageio.read(new file("webcam.jpg")); } grab (ioexception e) { e.printstacktrace(); } g.drawimage(img, 0, 0, 640, 480, this); repaint(); } }

don't read image in paintcomponent() method. read image in constructor.

also, don't phone call repaint() paintcomponent() method. if need continuously redraw, utilize thread or timer.

edit: might need tweaking, it's 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){ seek { synchronized(this){ img = imageio.read(new file("webcam.jpg")); } } grab (ioexception e) { e.printstacktrace(); } repaint(); seek { thread.sleep((long) (1000.0/30)); } grab (interruptedexception e) { e.printstacktrace(); } } } }

java swing repaint flicker

No comments:

Post a Comment