Using SwingWorker to perform a long calculation with results displayed in a GUI. - Java Swing

Java examples for Swing:Swing Thread

Description

Using SwingWorker to perform a long calculation with results displayed in a GUI.

Demo Code

import java.awt.Color;
import java.awt.GridLayout;
import java.util.concurrent.ExecutionException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

class BackgroundCalculator extends SwingWorker<Long, Object> {
  private final int n; // Fibonacci number to calculate
  private final JLabel resultJLabel; // JLabel to display the result

  public BackgroundCalculator(int n, JLabel resultJLabel) {
    this.n = n;//from  w w w .j  a v a 2s  . com
    this.resultJLabel = resultJLabel;
  }

  // long-running code to be run in a worker thread
  public Long doInBackground() {
    return fibonacci(n);
  }

  // code to run on the event dispatch thread when doInBackground returns
  protected void done() {
    try {
      // get the result of doInBackground and display it
      resultJLabel.setText(get().toString());
    } catch (InterruptedException ex) {
      resultJLabel.setText("Interrupted while waiting for results.");
    } catch (ExecutionException ex) {
      resultJLabel.setText("Error encountered while performing calculation.");
    }
  }

  // recursive method fibonacci; calculates nth Fibonacci number
  public long fibonacci(long number) {
    if (number == 0 || number == 1)
      return number;
    else
      return fibonacci(number - 1) + fibonacci(number - 2);
  }
}

public class Main extends JFrame {
  private final JPanel workerJPanel = new JPanel(new GridLayout(2, 2, 5, 5));
  private final JTextField numberJTextField = new JTextField();
  private final JButton goJButton = new JButton("Go");
  private final JLabel fibonacciJLabel = new JLabel();

  private final JPanel eventThreadJPanel = new JPanel(
      new GridLayout(2, 2, 5, 5));
  private long n1 = 0; // initialize with first Fibonacci number
  private long n2 = 1; // initialize with second Fibonacci number
  private int count = 1; // current Fibonacci number to display
  private final JLabel nJLabel = new JLabel("Fibonacci of 1: ");
  private final JLabel nFibonacciJLabel = new JLabel(String.valueOf(n2));
  private final JButton nextNumberJButton = new JButton("Next Number");

  public Main() {
    setLayout(new GridLayout(2, 1, 10, 10));
    workerJPanel.setBorder(new TitledBorder(new LineBorder(Color.BLACK),
        "With SwingWorker"));
    workerJPanel.add(new JLabel("Get Fibonacci of:"));
    workerJPanel.add(numberJTextField);
    goJButton.addActionListener(e -> {
      int n;
      try {
        n = Integer.parseInt(numberJTextField.getText());
      } catch (NumberFormatException ex) {
        fibonacciJLabel.setText("Enter an integer.");
        return;
      }
      fibonacciJLabel.setText("Calculating...");
      BackgroundCalculator task = new BackgroundCalculator(n, fibonacciJLabel);
      task.execute(); // execute the task
    });
    workerJPanel.add(goJButton);
    workerJPanel.add(fibonacciJLabel);

    // add GUI components to the event-dispatching thread panel
    eventThreadJPanel.setBorder(new TitledBorder(new LineBorder(Color.BLACK),
        "Without SwingWorker"));
    eventThreadJPanel.add(nJLabel);
    eventThreadJPanel.add(nFibonacciJLabel);
    nextNumberJButton.addActionListener(e -> {
      // calculate the Fibonacci number after n2
        long temp = n1 + n2;
        n1 = n2;
        n2 = temp;
        ++count;

        // display the next Fibonacci number
        nJLabel.setText("Fibonacci of " + count + ": ");
        nFibonacciJLabel.setText(String.valueOf(n2));
      });
    eventThreadJPanel.add(nextNumberJButton);

    add(workerJPanel);
    add(eventThreadJPanel);
    setSize(275, 200);
    setVisible(true);
  }

  public static void main(String[] args) {
    Main application = new Main();
    application.setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
}

Related Tutorials