我正在开发一个项目,我需要从相机读取条形码。我能够捕获图像并对其进行解码,但剩下的唯一问题是我需要“捕获和解码”过程才能工作,直到用户停止它。 所以我能实现的就是这个
btnCapture = new JButton("Capture");
btnCapture.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// camera is already initialized and ready to use
// take image from webcam
image = webcam.getImage();
// convert the image to show it on a label
lblNewLabel.setIcon((imageCont.convertToImageIcon(image,lblNewLabel)));
}
});
btnCapture.setBounds(508, 151, 89, 23);
add(btnCapture);
这个过程工作正常,但我需要它不是一次工作,而是当用户按下 btnCapture 时连续工作,我尝试了这个
while(true)
{
// camera is already initialized and ready to use
// take image from webcam
image = webcam.getImage();
// convert the image to show it on a label
lblNewLabel.setIcon((imageCont.convertToImageIcon(image,lblNewLabel)));
}
当我尝试此操作时,用户界面会卡住。请帮我解决这个问题,我对此进行了研究,并有了制作线程的想法,但我无法做到。
最佳答案
- 请勿为此目的向 JButton 添加 MouseListener,因为使用错误的监听器将导致错误行为,例如按钮即使已禁用,仍可正常工作。
- 使用 ActionListener。
- 对于重复操作,请使用 SwingWorker,并在 SwingWorker 的
doInBackground
方法中执行长时间运行的代码(即 while 循环)。这将在后台线程中运行此代码,并防止其卡住 Swing 事件线程。 - 您可以在 SwingWorker 仍在运行时使用 SwingWorker 的发布/处理方法对将完成的图像或图像结果传递回 GUI。
有关此内容的更多信息,请阅读 Lesson: Concurrency in Swing .
关于java - 循环更新图像而不影响其他框架工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33970940/