如何计算Jprogressbar的进度?

时间:2016-05-08 14:56:12

标签: java swing swingworker jprogressbar

不知何故,Jprogressbar正在移动,但是没有及时通过Swingworker的背景方法中的代码。任务在另一个Thread中完成,它可以工作。 我尝试使用while循环。 println最后没有打印。 ?  感谢

// this is part of a time consuming task
for (int j = 0; j < ba.length; j++) {
    String s1 = Integer.toHexString((ba[j] & 255) | 256).substring(1);
    s2 += s1;
} // instead of the while loop, now is working a for loop.
 for(int z = 0; z <= 100; z++) {
  Thread.sleep(50);
  setProgress(z);
 }
 /*int z = 0;
 while(z <= 100) {
    z++;
    Thread.sleep(50);
    setProgress(z); */
}  
System.out.println(s2); 

这是执行的完整示例。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PbTest extends JPanel implements ActionListener, PropertyChangeListener {

    private JProgressBar progressBar;
    private JButton startButton;
    private JTextArea taskOutput;
    private Task task;
    private String nameString;
    private String s2;
    private int timeFlow;
    private boolean done;
    private int z = 0;

    class Task extends SwingWorker<Void, Void> {
        /*
         * Main task. Executed in background thread.
         */
        @Override
        public Void doInBackground() throws InterruptedException {

            done = false;

            try {
                FileInputStream fis = new FileInputStream("timeConsuming.iso");

                MessageDigest md = MessageDigest.getInstance("MD5");

                byte[] b = new byte[1024];
                int i;
                while ((i = fis.read(b)) >= 0) {
                    md.update(b, 0, i);
                }
                while (i != -1)
                    fis.close();
                byte[] ba = md.digest();
                // while loop correct?
                while (ba.length <= 16) {
                    int z = 0;
                    while (z <= 100) {
                        z++;
                        Thread.sleep(50);
                        setProgress(z);
                    }
                }
                // System.out.print(i);
                for (int j = 0; j < ba.length; j++) {
                    String s1 = Integer.toHexString((ba[j] & 255) | 256).substring(1);
                    s2 += s1;
                }
                System.out.println(s2);
            } catch (IOException | NoSuchAlgorithmException ex) {
                Logger.getLogger(PbTest.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        } // System.out.println(javax.swing.SwingUtilities.isEventDispatchThread());

        /*
         * 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");
            done = true;
        }
    }

    public PbTest() {
        super(new BorderLayout());

        // Create the demo's UI.
        startButton = new JButton("Start");
        startButton.setActionCommand("start");
        startButton.addActionListener(this);

        progressBar = new JProgressBar(0, 100);
        // progressBar.setMinimum(0);
        // progressBar.setMaximum(100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5, 5, 5, 5));
        taskOutput.setEditable(false);

        JPanel panel = new JPanel();
        panel.add(startButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    }

    /**
     * Invoked when the user presses the start button.
     */
    public void actionPerformed(ActionEvent evt) {
        // progressBar.setIndeterminate(true);
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        // Instances of javax.swing.SwingWorker are not reusuable, so
        // we create new instances as needed.
        task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
    }

    /**
     * Invoked when task's progress property changes.
     */
    public void propertyChange(PropertyChangeEvent evt) {
       //this code block would work better with more gui components ?!
       /*if ("progress".equals(evt.getPropertyName())) {
     int progress = (Integer) evt.getNewValue();
     progressBar.setValue(progress);
     ls.setText(String.format(
                "Completed %d%% of task.\n", task.getProgress()));
    } */
        if (!done) {
            int progress = task.getProgress();
            progressBar.setValue(progress);
            System.out.println(String.format("Completed %d%% of task.\n", task.getProgress()));
        }
    }

    /**
     * Create the GUI and show it. As with all GUI code, this must run on the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        // Create and set up the window.
        JFrame frame = new JFrame("ProgressBarDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create and set up the content pane.
        JComponent newContentPane = new PbTest();
        newContentPane.setOpaque(true); // content panes must be opaque
        frame.setContentPane(newContentPane);

        // Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

0 个答案:

没有答案