2

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
kw3rti
  • 204
  • 2
  • 11

1 Answers1

4

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • One up for the L&F hint: I encountered "special" Look&Feels that explicitly checked whether they are used only on the EDT (and threw up otherwise). So although starting directly from the `main` will work in *most* cases, one should **always** start from the EDT to be on the safe side. – Marco13 Mar 14 '15 at 19:37
  • Thanks very much for the reply. I'm still trying to get my head around the event dispatching thread. Why is it ok to extend JPanel and not JFrame? – kw3rti Mar 14 '15 at 20:00