import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.util.concurrent.*; import javax.swing.*; public class SwingWorkerTest { public static void main(String[] args) throws Exception { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new SwingWorkerFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } /** * This frame has a text area to show the contents of a text file, a menu to open a file and cancel * the opening process, and a status line to show the file loading progress. */ class SwingWorkerFrame extends JFrame { public SwingWorkerFrame() { chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); textArea = new JTextArea(); add(new JScrollPane(textArea)); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); statusLine = new JLabel(" "); add(statusLine, BorderLayout.SOUTH); JPanel panel = new JPanel(); add(panel, BorderLayout.NORTH); openButton = new JButton("Open"); panel.add(openButton); openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { // show file chooser dialog int result = chooser.showOpenDialog(null); // if file selected, set it as icon of the label if (result == JFileChooser.APPROVE_OPTION) { textArea.setText(""); openButton.setEnabled(false); final File file = chooser.getSelectedFile(); Thread background = new Thread(new Runnable() { public void run() { try { Scanner in = new Scanner(new FileInputStream(file)); final int[] lineNumber = new int[1]; while (in.hasNextLine()) { final String line = in.nextLine(); lineNumber[0]++; EventQueue.invokeLater(new Runnable() { public void run() { statusLine.setText("" + lineNumber[0]); textArea.append(line); textArea.append("\n"); } }); } } catch (IOException ex) { ex.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run() { openButton.setEnabled(true); } }); } }); background.start(); } } }); exitButton = new JButton("Exit"); panel.add(exitButton); exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); } private JFileChooser chooser; private JTextArea textArea; private JLabel statusLine; private JButton openButton; private JButton exitButton; public static final int DEFAULT_WIDTH = 450; public static final int DEFAULT_HEIGHT = 350; }