在不影响其他帧工作的情况下循环更新图像

Update image in a loop without effecting other frame's work

我正在做一个项目,我需要从相机读取条码。我能够捕获图像并对其进行解码,但唯一剩下的问题是我需要 'capture and decode' 进程工作直到用户停止它。 所以我能做到的是这个

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

当我尝试这个时,这会冻结 UI。请帮助我解决这个问题,我对此进行了研究并有了制作线程的想法,但我做不到。

  1. 不要为此目的将 MouseListener 添加到 JButton,因为使用错误的侦听器会导致错误行为,例如即使按钮被禁用,它仍然可以正常工作。
  2. 使用 ActionListener。
  3. 对于重复的动作,使用SwingWorker,并在SwingWorker的doInBackground方法中执行long-运行ning代码,while循环。这将 运行 此代码放在后台线程中,并防止它冻结 Swing 事件线程。
  4. 您可以使用 SwingWorker 的 publish/process 方法对将完成的图像或图像的结果传递回 GUI,同时 SwingWorker 仍然 运行ning。

有关此的更多信息,请阅读 Lesson: Concurrency in Swing