Search code examples
javamultithreadingswinggraphicsinvokelater

Should the first JFrame be created with 'invokeLater' or can it be created directly from main?


I've recently started learning how to use Swing and graphics in Java and have come across two different approaches for designing a GUI.

1) To have the program's main method in an instatiation of the JFrame class.

2) To have a class which calls SwingUtilities.invokeLater() at the end of the main method to delay the thread that deals with graphics until after the initialisation of the main method.

e.g. 1.

class program extends JFrame {
   public static void main(String[] args) {....}
}

e.g. 2.

class program implements Runnable {
  public static void main() {
    program p = new program();
    SwingUtilities.invokeLater(p);
  }
  public void run() { ... }
}

How important is it to make the program thread safe as in approach 2? Also, what are the advantages and disadvantages of each approach? i.e. When would you use one approach over the other? etc.


Solution

  • I have run into simple Swing applications that fail outright if not started on the Swing event thread, this happened first for me when setting look and feel. Also correct running is not guaranteed in any situation unless the GUI is started on the Swing event thread, and so for general Swing advice, I recommend

    • Always try to start your GUI on the Swing event thread.
    • Avoid extending JFrame as it's almost never needed, and limits your code.
    • Do extend JPanel if your GUI does graphics, especially if it does animation
    • Or if you want to have more control over setting the size of your GUI, and override getPreferredSize() for this.

    You can paint yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding. You also never will want to draw directly in a JFrame as this risks mis-drawing one of its critical components but do often draw in JPanels, especially if doing animation, and for this you will need to extend JPanel.