简体   繁体   中英

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

I am working on a project and I needed to read barcode from camera. I am able to capture images and decode them but only problem remaining is that I need the 'capture and decode' process to work until user stops it. So for what I could achieve is this

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

this process is working fine but I need it to work not once but continuously when the user press btnCapture for that I tried this

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

When I tried this this freezes the UI. please help me with this I researched about it and got the idea of making a thread but I could not make it.

  1. Don't add a MouseListener to a JButton for this purpose, as this use of the wrong listener will result in misbehaviors, such as the button still functioning even though its disabled.
  2. Use an ActionListener.
  3. For the repeated actions, use a SwingWorker, and do the long-running code, the while loop, within the SwingWorker's doInBackground method. This will run this code in a background thread, and will prevent it from freezing the Swing event thread.
  4. You can use the SwingWorker's publish/process method pair to pass completed images or results from images back to the GUI while the SwingWorker is still running.

For more on this, please read Lesson: Concurrency in Swing .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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