Simple code from java.sun:
public class BasicApp implements Runnable {
JFrame mainFrame;
JLabel label;
public void run() {
mainFrame = new JFrame("BasicApp");
label = new JLabel("Hello, world!");
label.setFont(new Font("SansSerif", Font.PLAIN, 22));
mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
mainFrame.setVisible(false);
// Perform any other operations you might need
// before exit.
System.exit(0);
}
});
mainFrame.add(label);
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args) {
Runnable app = new BasicApp();
try {
SwingUtilities.invokeAndWait(app);
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
I can put all of this method into main(), but why do I need a separate run method that also implements the runnable to execute it? What is the idea behind this concept? Thanks.
From Oracle SDN: Threads and Swing
The gist of it is that the code needs to be run when Swing is good and ready to run it. Not necessarily right when you call it.