Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
import java.awt.*;
import javax.swing.*
import java.awt.event.*;

class MyGUIApp extends JFrame {

    // Use fields for GUI components that need to be referenced outside of the GUI initialization process (initGUI)

    /**
     * Constructor for the GUI.
     */
    public MyGUIApp() {
        // initialize fields here.  Surrounding your code in a protective try-catch is recommended.

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Causes the application to end if the GUI frame is closed.
        initGUI();  // initialize the GUI components
    }

    /**
     * Actually start the GUI
     */
    public void start() {
       // Do any last second initializations, if needed.
       setVisible(true);  // Make the GUI visible
    }

    /**
     * Initialize the GUI components
     */
    private void initGUI() {
        Container contentPane = getContentPane(); // all GUI components are added to the frame's ContentPane.
                                                  // You can also just call the accessor each time as well and not use a local variable.

        // instantiate, initialize and connect all the GUI's components here.
        // Don't forget to add them to the container that holds them, e.g. the ContentPane.

    }

    /**
     * Main method that starts the app.
     * In general, this would not be in this class but rather in a separate "controller" class
     * with slightly different coding (as required for a true Model-View-Controller system).
     * We put it here for now, for simplicity's sake only.
     */
    public static void main(String[] args) {
        // initialize and start the GUI on the GUI thread.
        SwingUtilities.invokeLater(new Runnable() {
	   public void run() {
              MyGUIApp view = new MyGUIApp();  // instantiate the GUI but don't show it yet.
              // Model classes would be instantiated here plus any other required objects.
              view.start();  // Start the application by making the GUI visible.
           }
        }
    }
}

Some typical GUI initializations:

...