1

Somehow the Jprogressbar is moving, but not in time with the code in the background method thru Swingworker. The task is done in another Thread, it works. I tried to use a while loop. println is not printing at the end. ? Thanks

// 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); 

here is the full example to execute.

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();
            }
        });
    }
}
loadP
  • 404
  • 1
  • 4
  • 15
  • Closed as a duplicate. If you feel that it's not a duplicate, then please improve your question including creating and posting a valid [mcve] (please read the link). – Hovercraft Full Of Eels May 08 '16 at 14:58
  • I modified my post, hope it's better now, should be different.Thanks – loadP May 08 '16 at 16:12
  • Question re-opened. Posted code formatted for site. – Hovercraft Full Of Eels May 08 '16 at 16:30
  • You're not changing `ba` within the while loop that tests its length, and this greatly confuses me. Why have you written it this way? – Hovercraft Full Of Eels May 08 '16 at 16:33
  • And if the loop keeps repeating, then it looks like your progress property will repeatedly go from 0 to 100 ad infinitum. What do you want to use to measure progress? What will determine when the progress has been fully completed? These are the key questions in my mind. – Hovercraft Full Of Eels May 08 '16 at 16:35
  • Also note that we cannot execute your code since it requires a specific file for execution. – Hovercraft Full Of Eels May 08 '16 at 16:36
  • Thanks. Yes I was thinking the same what to implement to measure the progress. The algorithm calculate a files hash. However I'm not sure were to link it, to count the progress? The code could be used in an ide. – loadP May 08 '16 at 16:57
  • Seems to work now, as I changed the loop from while to for. Thank you very much. – loadP May 08 '16 at 22:52
  • No, it just runs the time of the loop(from when the loop starts 10-20 seconds), but not the real task time ? Thanks – loadP May 11 '16 at 14:19

0 Answers0