FileDocCategorySizeDatePackage
UpdateSlowGUI.javaAPI DocExample3962Thu Mar 25 21:30:24 GMT 2004None

UpdateSlowGUI

public class UpdateSlowGUI extends JFrame
Update a GUI after some slow operation completes. Do it right, using the AWT event thread.

Fields Summary
Constructors Summary
public UpdateSlowGUI()

		super("UpdateSlowGUI");
		final JButton b;
		final JLabel status;
		Container cp = getContentPane();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		cp.add(BorderLayout.CENTER, b = new JButton("Update..."));
		cp.add(BorderLayout.SOUTH, status = new JLabel("Ready"));
		b.addActionListener(new ActionListener() {
			// Pressed when the user wants to do the action...
			public void actionPerformed(ActionEvent evt) {
				status.setText("Busy...");
				b.setEnabled(false);
				Thread t = new Thread() {
					public void run() {
						// Simulate something slow, like a large DB query
						try {
							Thread.sleep(5000);
						} catch(InterruptedException ex) {
							return;
						}

						// OK, the long-running thing has finished.
						// Now go back into AWT/Swing to update the GUI
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								status.setText("Ready");
								b.setEnabled(true);
							}
						});
					}
				};
				t.start();
			}
		});
		setSize(150, 200);
		setLocation(200, 200);
	
Methods Summary
public static voidmain(java.lang.String[] args)

		// Create the GUI; will implicitly create and start AWT GUI thread
		new UpdateSlowGUI().setVisible(true);