试图阻止Swingworker [英] Trying to stop swingworker

查看:77
本文介绍了试图阻止Swingworker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的JDialog,当我的SwingWorker线程启动时会弹出.该对话框只有一个JProgressbar和一个Button(取消按钮).我试图弄清楚如何取消我的SwingWorker,但是没有运气.我认为我走在正确的道路上.我写了一个cancel方法,现在我只需要弄清楚按下按钮时如何调用它.代码在下面...

I have a custom JDialog that pops up when my SwingWorker thread fires up. The dialog just has a JProgressbar and a Button (cancel button). I am trying to figure out how to cancel my SwingWorker, but am having no luck. I think I am on the right path though. I wrote a cancel method, now I just need to figure out how to call it when the button is pushed. Code is below...

            btn_Cancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) 
                {
                   //trying to access cancel()
                }
             });

        SwingWorker worker = new SwingWorker<String, Void>() { 
        @Override
        protected String doInBackground() throws Exception {
                while (runLoad.getState() != Thread.State.TERMINATED &&      !isCancelled()) {
                    try {
                        synchronized (this) {
                            Thread.sleep(2000);
                        }
                    } catch (InterruptedException e){}
                }
                return null;
            }
        @Override
        public void done() {
                try {
                   get(); 
                } catch (InterruptedException | ExecutionException ex) {
                    JOptionPane.showMessageDialog(null,
                    "Somethings Wrong: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }
              Progress.setVisible(false);
              Progress.dispose();
            }
        public void cancel(SwingWorker worker){
            worker.cancel(true);
         }
       };
       worker.execute();

推荐答案

您的取消按钮应调用SwingWorker#cancel方法

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

请注意,在创建ActionListener

这篇关于试图阻止Swingworker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆