import javax.swing.*; import java.awt.*; import java.awt.event.*; public class LongOperation extends JFrame { JLabel progressInfo; JButton start; public static void main(String[] args) { new LongOperation(); } public LongOperation() { addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); System.exit(0); } }); // Create a button and a label and add them to the JFrame. start = new JButton("Start long operation"); Container c = getContentPane(); c.setLayout(new FlowLayout()); c.add(start); progressInfo = new JLabel("waiting for click"); c.add(progressInfo); //Listen to ActionEvents from the button. start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { //The user has started the operation. progressInfo.setText("working..."); start.setEnabled(false); //This operation will take a long time, so we must start a new //thread and update the screen when it's done. If we did not //start a new thread the event-dispath thread would be blocked //until the operation was finished. And if the event-dispath //thread is blocked, the whole user interface is blocked. Thread doIt = new Thread() { public void run() { //This takes a long time. try { sleep(5000); } catch (InterruptedException e) { } //Place GUI update on the event queue. SwingUtilities.invokeLater(new Runnable() { public void run() { progressInfo.setText("Done!"); start.setEnabled(true); } }); } }; doIt.start(); } }); setSize(300, 200); setVisible(true); } }