Java SwingWorker get return value from time consuming task
import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutionException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingWorker; class MyPanel extends JPanel { public MyPanel() { setLayout(new BorderLayout()); // build buttons start and cancel JPanel buttonsArea = new JPanel(new FlowLayout(FlowLayout.RIGHT)); final JButton startButton = new JButton("Start"); final JButton cancelButton = new JButton("Cancel"); cancelButton.setEnabled(false);/*from www . ja v a2 s.co m*/ buttonsArea.add(startButton); buttonsArea.add(cancelButton); // create the buttons area add(buttonsArea, BorderLayout.SOUTH); // build status area final JTextArea textArea = new JTextArea(5, 15); textArea.setEditable(false); JScrollPane statusScroll = new JScrollPane(textArea); add(statusScroll, BorderLayout.CENTER); // spawn a worker thread startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { startButton.setEnabled(false); textArea.setText(""); cancelButton.setEnabled(true); SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>() { @Override protected Integer doInBackground() throws Exception { Thread.sleep(2000); int pk = new Random().nextInt(); return pk; } @Override protected void done() { try { System.out.println("Primary key = " + get()); textArea.setText("Primary key = " + get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } startButton.setEnabled(true); } }; worker.execute(); } }); // cancel button will kill worker and reset. cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { startButton.setEnabled(true); cancelButton.setEnabled(false); } }); } } public class Main { public static void main(String[] args) { // create frame for Main JFrame frame = new JFrame("java2s.com"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new MyPanel()); frame.setSize(300, 250); frame.setVisible(true); } }