Question

I'm writing a small function that will update my ProgressBar and a JLabel base on weighted random integers. The thread is sleeping correctly and the random values are coming through, however, my progress bar and jlabel are not updating.

It is also leaving my GUI unresponsive. It isn't locking my GUI completely (I'm able to click buttons, but it doesn't execute the functions associated with those buttons).

Throwing a print statement in the run() method is not printed out. So I'm thinking it never gets in there.

Here is my method so far:

private void updateProgressBar(int max) {
    final int maxDiamonds = max;
    int i = 0;
    while(i <= max) {
        //get random obstacle found
        final Obstacle o = obstacle.next();
        System.out.println("Obstacle: " + o.getName());
        //get random number of diamonds for obstacle
        int numDiamonds = Integer.parseInt(numFoundDiamonds.next());
        System.out.println("Number of Diamonds: " + numDiamonds);
        //set currentValue for the progress bar
        final int currentValue = i;

        for(int j = o.getRemovalTime(); j >= 0; j--) {
            final int rSecs = j;
            System.out.println("Time remaining to remove: " + rSecs);
            try {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        progressBar.setString(currentValue + "/" + maxDiamonds);
                        statusLabel.setText("Found " + o.getName() + ". Removing: " + rSecs + " s Remaining.");
                    }
                });
                java.lang.Thread.sleep(1000);
            } catch (InterruptedException e) {
                JOptionPane.showMessageDialog(this, e.getMessage());
            }
        }
        i += numDiamonds;  
    }

}

Perhaps I'm overlooking something simple.

I can also provide more code regarding the other classes used, but I feel that the issue lies in the code provided.

Was it helpful?

Solution

You're calling Thread.sleep(...) on the Swing event thread which will put the whole Swing thread and application to sleep. Use a background thread such as with a SwingWorker.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top