如何使用Swingworker显示进度栏?

问题描述 投票:0回答:1

**这是我的代码段。单击按钮后,它将在后台执行加载程序,但是我无法在进度栏中获取任务的详细信息。任何人都可以告诉我我在这里缺少什么吗?**重点是我不想在我的doInBackground方法中包含所有插入代码.. ****

public class ProgressBarDemo extends JPanel
                             implements ActionListener, 
                                        PropertyChangeListener {
private JProgressBar progressBar;
private JButton startButton;
private JTextArea taskOutput;
private Task task;

class Task extends SwingWorker<Void, Integer> {
    @Override
    protected void process(List<Integer> arg0) {
        // TODO Auto-generated method stub
        super.process(arg0);
        for(int k:arg0)
        System.out.println("arg is "+k);
        setProgress(arg0.size()-1);
    }

    /*
     * Main task. Executed in background thread.
     */
    @Override
    public Void doInBackground() throws Exception {
        Random random = new Random();
        int progress = 0;
        //Initialize progress property.
        setProgress(0);
        Thread.sleep(100);
        new LoadUnderwritingData().filesinfolder("D:\\files to upload\\");
        System.out.println("records inserted are "+LoadData.records_count_inserted);
        publish(LoadData.records_count_inserted);
        /*
         * while (progress < 100) { //Sleep for up to one second. try {
         * Thread.sleep(random.nextInt(1000)); } catch (InterruptedException ignore) {}
         * //Make random progress. progress += random.nextInt(10);
         * setProgress(Math.min(progress, 100)); }
         */
        return null;
    }

    /*
     * Executed in event dispatching thread
     */
    @Override
    public void done() {
        Toolkit.getDefaultToolkit().beep();
        startButton.setEnabled(true);
        setCursor(null); //turn off the wait cursor
        taskOutput.append("Done!\n");
    }
}
java multithreading swing desktop-application swingworker
1个回答
0
投票

我看到你没有打progressBar.setValue(progress);。同样,您需要在每个插入的元素之后调用publish(currentInsertCount);。在处理方法中,您可以执行以下操作:

// assuming you are passing the current insert count to publish()
for (int k : arg0){
    System.out.println("arg is " + k);
    progressBar.setValue(k);
}

但是从您现在发布的内容来看,还不清楚在哪里进行处理。这行是吗:

new LoadUnderwritingData().filesinfolder("D:\\files to upload\\");

如果是,则必须将一些回调传递给filesinfolder("..."),以便它可以更新进度。

注意:在普通的新线程中执行而不是使用SwingWorker可能会更容易。

我将如何使用普通线程:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;

public class ProgressBarDemo extends JPanel implements ActionListener {

    private JProgressBar progressBar;
    private JButton startButton;
    private JTextArea taskOutput;


    public static void main(String[] args) {
        JFrame frame = new JFrame("ProgressBarDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setPreferredSize(new Dimension(500, 500));
        frame.add(new ProgressBarDemo());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public ProgressBarDemo(){
        progressBar = new JProgressBar(0, 100);
        startButton = new JButton(">");
        taskOutput = new JTextArea();

        startButton.addActionListener(this);

        setLayout(new BorderLayout());
        add(startButton, BorderLayout.NORTH);
        add(taskOutput, BorderLayout.CENTER);
        add(progressBar, BorderLayout.SOUTH);

        progressBar.setVisible(false);
    }

    public void upload(File directory){
        startButton.setEnabled(false);
        progressBar.setVisible(true);
        new Thread() {

            @Override
            public void run() {
                taskOutput.append("Discovering files...\n");
//              List<File> files = Arrays.asList(directory.listFiles()); // if you want to process both files and directories, but only in the given folder, not in any sub folders
//              List<File> files = Arrays.asList(getAllFiles(directory)); // if you only want the files in that directory, but not in sub directories
                List<File> files = getAllFilesRecursive(directory); // if you want all files
                taskOutput.append("  -> discovered " + files.size() + " files.\n");
                progressBar.setMaximum(files.size());
                int processedCount = 0;
                taskOutput.append("Processing files...\n");
                for(File file : files){
                    try {
                        byte[] bytes = Files.readAllBytes(file.toPath());
                        // TODO: process / upload or whatever you want to do with it
                    } catch (Throwable e) {
                        taskOutput.append("Failed to process " + file.getName() + ": " + e.getMessage() + "\n");
                        e.printStackTrace();
                    } finally {
                        processedCount++;
                        progressBar.setValue(processedCount);
                    }
                }
                taskOutput.append("  -> done.\n");
                startButton.setEnabled(true);
                progressBar.setVisible(false);
            }
        }.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        upload(new File("C:\\directoryToUpload"));
    }

    /**
     * Gets all normal files in the directory.
     */
    public static File[] getAllFiles(File directory){
        return directory.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname.isFile();
            }
        });
    }

    /**
     * Gets all normal files in the given directory and its sub directories.
     */
    public static List<File> getAllFilesRecursive(File directory){
        List<File> result = new ArrayList<File>();
        getAllFilesRecursive(directory, result);
        return result;

    }

    private static void getAllFilesRecursive(File directory, List<File> addTo){
        if(directory.isFile()){
            addTo.add(directory);
        }else if (directory.isDirectory()){
            File[] subFiles = directory.listFiles();
            if(subFiles == null) return;
            for(File subFile : subFiles){
                getAllFilesRecursive(subFile, addTo);
            }
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.