Skip to content

Instantly share code, notes, and snippets.

@kaydell
Created September 25, 2013 20:20
Show Gist options
  • Save kaydell/6705452 to your computer and use it in GitHub Desktop.
Save kaydell/6705452 to your computer and use it in GitHub Desktop.
Using Multiple Threads With a Swing GUI
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
/**
* This class is an example of how to correctly startup a GUI interface
*
* From Oracle's Java Tutorial:
* http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
*
* @author kaydell
*
*/
public class SwingGUIDemo extends JFrame {
/**
* This constructor creates a simple window
*/
public SwingGUIDemo() {
// add a label to this window
JLabel jLabel = new JLabel("Hello Multithreading", JLabel.CENTER);
this.add(jLabel);
// finish initializing this window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // exit app when this window is closed. Good when there's only one window
setSize(500,200); // size this window
setLocationRelativeTo(null); // center this window
}
/**
* This main method is rather complex, but it demonstrates the correct way to
* start a Swing GUI. This way of creating a GUI window is especially necessary
* when using multiple threads.
*
* @param args Not used
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SwingGUIDemo demoFrame = new SwingGUIDemo();
demoFrame.setVisible(true); // setVisible(true) should be called last
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment