Trying to stop swingworker

爱⌒轻易说出口 提交于 2019-11-29 12:59:04

Your cancel button should call the SwingWorker#cancel method

final SwingWorker worker = ...;

btn_Cancel.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent e) {
    worker.cancel( true );
  }
});

In your worker, you have to make sure to check the cancel flag

SwingWorker worker = new SwingWorker<String, Void>() { 
  @Override
  protected String doInBackground() throws Exception {
    while ( !isCancelled() ) {
      //do your stuff
    }
  }
}

Note that you need to create the worker before you create your ActionListener

As explained in the official documentation, you need to check isCancelled() in your SwingWorker callback method.

You could call

worker.cancel(true);

in your button action listener?

You should call

worker.cancel(true); //this will set the cancel flag of the worker

Then, when you invoke isCancelled() this will return true. So, you Can check this state in your loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!