// This code example is created for educational purpose
// by Thorsten Thormaehlen (contact: www.thormae.de).
// It is distributed without any warranty.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

class MyGui extends JFrame implements ActionListener {
  
  final JProgressBar progressBar = new JProgressBar(0, 100);
  final JButton button = new JButton("Compute");
  boolean userStopped = false;
  boolean threadAlive = false;
  int percent;
  
  public void createGUI() {
    setTitle("HelloGUI");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(320, 240);

    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout());
    
    button.addActionListener(this);
    button.setBounds(120, 30, 150, 30);
    contentPane.add(button);
    
    progressBar.setValue(0);
    progressBar.setStringPainted(true);
    contentPane.add(progressBar);
    
    setVisible(true);
  }

  Runnable updateUI = new Runnable() {
    @Override
    public void run() {
      if(percent < 100) {
        progressBar.setString("Computing " + percent + "%");
        button.setText("Stop");
      }else{
        progressBar.setString("Done");
        button.setText("Compute");
      }
      progressBar.setValue(percent);
    }
  };

  Runnable workerThread = new Runnable() {
    @Override
    public void run() {

      for (int i=0; i < 100 && !userStopped; i++) {
        try {
          Thread.sleep(50); // compute something here
          percent = i;
          // run updateUI in the Event Dispatching Thread
          SwingUtilities.invokeLater(updateUI); 
        } catch (InterruptedException e) {}
      }
      percent = 100;
      SwingUtilities.invokeLater(updateUI);
      threadAlive = false;
    }
  };

  public void actionPerformed(ActionEvent event) {
    if(!threadAlive) {
      threadAlive = true;
      userStopped = false;
      new Thread(workerThread).start(); 
    } else {
      userStopped = true;
    }
  }
}

public class MyProgressBar {
  public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        MyGui myGUI = new MyGui();
        myGUI.createGUI();
      }
    });
  }
}
