Use SwingWorker to run task - Java Swing

Java examples for Swing:Swing Thread

Description

Use SwingWorker to run task

Demo Code

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

class DiceWorker extends SwingWorker {
  int timesToRoll;
  public DiceWorker(int timesToRoll) {
    super();//from   w  w  w.ja v a  2s.  c o m
    this.timesToRoll = timesToRoll;
  }
  protected int[] doInBackground() {
    int[] result = new int[16];
    for (int i = 0; i < this.timesToRoll; i++) {
      int sum = 0;
      for (int j = 0; j < 3; j++) {
        sum += Math.floor(Math.random() * 6);
      }
      result[sum] = result[sum] + 1;
    }
    return result;
  }
}

public class Main extends JFrame implements ActionListener,
    PropertyChangeListener {
  JTextField[] total = new JTextField[16];
  JButton roll;
  JTextField quantity;
  DiceWorker worker;

  public Main() {
    super("Dice Roller");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(850, 845);
    JPanel topPane = new JPanel();
    GridLayout paneGrid = new GridLayout(16, 1);
    topPane.setLayout(paneGrid);
    for (int i = 0; i < 16; i++) {
      total[i] = new JTextField("0", 4);
      JLabel label = new JLabel((i + 3) + ": ");
      JPanel cell = new JPanel();
      cell.add(label);
      cell.add(total[i]);
      topPane.add(cell);
    }
    JPanel bottomPane = new JPanel();
    JLabel quantityLabel = new JLabel("Times to Roll: ");
    quantity = new JTextField("0", 5);
    quantity.setText("1000");
    roll = new JButton("Roll");
    roll.addActionListener(this);
    bottomPane.add(quantityLabel);
    bottomPane.add(quantity);
    bottomPane.add(roll);

    // set up frame
    GridLayout frameGrid = new GridLayout(2, 1);
    setLayout(frameGrid);
    add(topPane);
    add(bottomPane);

    setVisible(true);
  }
  public void actionPerformed(ActionEvent event) {
    int timesToRoll;
    try {
      timesToRoll = Integer.parseInt(quantity.getText());

      worker = new DiceWorker(timesToRoll);
      worker.addPropertyChangeListener(this);
      worker.execute();
    } catch (Exception exc) {
      System.out.println(exc.getMessage());
      exc.printStackTrace();
    }
  }
  public void propertyChange(PropertyChangeEvent event) {
    try {
      int[] result = (int[]) worker.get();
      for (int i = 0; i < result.length; i++) {
        total[i].setText("" + result[i]);
      }
    } catch (Exception exc) {
      exc.printStackTrace();
    }
  }

  public static void main(String[] arguments) {
    new Main();
  }
}

Related Tutorials