有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java重复SwingWorker

我想构建一个JFrame能够在每次单击JButton时运行后台任务。目前我使用的是swing worker,它不允许任务执行多次

如何使用JButton单击为SwingWorker启用重复任务

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) 个答案

  1. # 1 楼答案

    currently i am using a swing worker and it wont allow the task to be executed more than once.

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


    编辑您声明:

    but i have no idea how to reinvent the swingworker everytime the user click the scan button.

    你如何“改造”任何对象?通过创建一个新实例,这里是一个新的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运行期间可能发生的任何异常