Use SwingWorker to wrap time consuming task : SwingWorker « Swing JFC « Java






Use SwingWorker to wrap time consuming task

     

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;

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

public class PrimeCheck extends JFrame {
  public PrimeCheck() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    JPanel pnl = new JPanel();
    JButton btnCheck = new JButton("Check");
    ActionListener al;
    al = new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        try {
          BigInteger bi = new BigInteger("1234567");
          System.out.println("One moment...");
          new PrimeCheckTask(bi).execute();
        } catch (NumberFormatException nfe) {
          System.out.println("Invalid input");
        }
      }
    };
    btnCheck.addActionListener(al);
    pnl.add(btnCheck);
    getContentPane().add(pnl, BorderLayout.NORTH);
    pack();
    setResizable(false);
    setVisible(true);
  }

  public static void main(String[] args) {
        new PrimeCheck();
  }
}

class PrimeCheckTask extends SwingWorker<Boolean, Void> {
  private BigInteger bi;

  PrimeCheckTask(BigInteger bi) {
    this.bi = bi;
  }

  @Override
  public Boolean doInBackground() {
    return bi.isProbablePrime(1000);
  }

  @Override
  public void done() {
    try {
        boolean isPrime = get();
        if (isPrime)
          System.out.println("Integer is prime");
        else
          System.out.println("Integer is not prime");
    } catch (Exception ee) {
      System.out.println("Unable to determine primeness");
    }
  }
}

   
    
    
    
  








Related examples in the same category

1.Use SwingWorker to perform background tasks
2.SwingWorker in Java 6
3.Generic class to dispatch events in a highly reliable way.
4.Detect Event Dispatch Thread rule violations
5.Process On Swing Event Thread
6.A pool of work threads
7.3rd version of SwingWorker
8.This program demonstrates a swing-worker thread that runs a potentially time-consuming task