重复SwingWorker

时间:2014-10-28 02:05:04

标签: java multithreading swing jframe swingworker

我想构建一个JFrame,每次点击JButton时都能运行后台任务。目前我正在使用摇摆工作者,它不会允许任务执行多次。

如何通过SwingWorker点击启用JButton的重复任务。

public class ScanFileFrame extends JFrame{

    JButton btnTicking;
    JLabel label1;

    ScanFileFrame(){

        JFrame jframe = new JFrame();
        jframe.setLayout(new FlowLayout());
        btnTicking = new JButton("Start Scanning Files");
        label1 = new JLabel("No File Scanned");

        btnTicking.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                worker.execute();

            }   
        });

        jframe.add(btnTicking);
        jframe.add(label1);

        jframe.setVisible(true);
        jframe.setSize(300,300);
    }

    SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {

        @Override
        protected Boolean doInBackground() throws Exception {

           // Simulate scan file
           System.out.println("scanning files ....");
           Thread.sleep(2000);

           return true;

        }

        //update jframe jlabel when background task finish
        protected void done() {
            label1.setText("Files Scanned");
            System.out.println("complete");
        }
    };

    public static void main(String[] args){
        ScanFileFrame f = new ScanFileFrame();

    }
}

1 个答案:

答案 0 :(得分:5)

  

目前我正在使用摇摆工作者,它不会允许任务执行多次。

这不是问题,因为您只需构建一个新的SwingWorker并在JButton的ActionListener中运行它。据我所知,这个 是您当前编写的问题的解决方案。如果您需要更详细的答案,那么您需要在问题中提供更多详细信息。


修改您声明:

  

但我不知道每次用户点击扫描按钮时如何重新发明swingworker。

你如何“重塑”任何物体?通过创建一个新实例,这里是一个新的MySwingWorker,然后在其上调用execute。


如,

import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;

import javax.swing.*;

public class ScanFileFrame {
   private FileScanAction fileScanAction = new FileScanAction("Scan Files", KeyEvent.VK_S);
   private JButton btnTicking = new JButton(fileScanAction);
   private JLabel label1;
   private MyFileScanWorker worker;

   ScanFileFrame() {

      JFrame jframe = new JFrame();
      jframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      jframe.setLayout(new FlowLayout());
      label1 = new JLabel("       No File Scanned       ", SwingConstants.CENTER);

      jframe.add(btnTicking);
      jframe.add(label1);
      jframe.pack();
      jframe.setLocationByPlatform(true);
      jframe.setVisible(true);

   }

   @SuppressWarnings("serial")
   private class FileScanAction extends AbstractAction {
      public FileScanAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         label1.setText("Scanning Files");
         fileScanAction.setEnabled(false);
         worker = new MyFileScanWorker();
         worker.addPropertyChangeListener(new WorkerListener());
         worker.execute();
      }
   }

   private class WorkerListener implements PropertyChangeListener {
      @Override
      public void propertyChange(PropertyChangeEvent pcEvt) {
         if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
            fileScanAction.setEnabled(true);
            try {
               boolean success = worker.get();
               String text = success ? "Scanning Successful" : "Scanning Error";
               label1.setText(text);
            } catch (InterruptedException | ExecutionException e) {
               e.printStackTrace();
            }
         }
      }
   }

   private class MyFileScanWorker extends SwingWorker<Boolean, Void> {

      @Override
      protected Boolean doInBackground() throws Exception {
         // Simulate scan file
         Thread.sleep(2000);

         // have it work successfully 2/3 of the time.
         if (Math.random() > 0.3333) {
            return true;
         } else {
            return false;
         }
      }
   };

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            new ScanFileFrame();
         }
      });
   }
}

请注意,您总是希望在SwingWorker完成后调用get(),即使它返回null,这样您就可以捕获在SwingWorker运行期间可能发生的任何异常。