Java Basics

Responsibilities of main and JFrame subclass constructor

Every class has certain responsibilities. Sometimes assigning these responsibilities is easy, and sometimes boundary cases are unclear. You'll see variation in the placement of JFrame initialization statements.

Because you might want to have a splash screen, it seems that determining when the window is made visible is the job of the master coordinating method (main). Similarly, exactly what action is taken when the window is closed also belongs with the controlling method. You will sometimes see these actions in the JFrame constructor, but my feeling is that it belongs in the controlling framework (main).

Here is how the Tiny Window Subclass might be written with all initialization in the JFrame subclass. These few statements are so easy to move that it doesn't seem like much to worry about for simple programs.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
// File   : gui-tutorial/tw2/TinyWinSubclass.java
// Purpose: I don't like it, but here's an alternative
//          placement of JFrame initialization statements.
// Author : Fred Swartz
// Date   : 2005-06-17

import javax.swing.*;

class TinyWinSubclass {
    public static void main(String[] args) {
        new TinyWinGUI();                        //Note 1
    }
}


class TinyWinGUI extends JFrame {
    public TinyWinGUI() {
        setTitle("Tiny Window using JFrame Subclass");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

Notes

  1. Everything is done in the constructor. NOT the style that will be used. This is only to show a common alternative.