Java Basics

Subclass JFrame, JPanel, or no subclass?

JFrame subclass. The most common way to define a window is to create a class which extends JFrame, and build the GUI in the constructor of that class. Most of these example programs use this style because it works reasonably well and is the most popular. Therefore it's important to become familiar with it to be able to read other programs comfortably.

In main() with no subclass. Building a GUI entirely in a static main program is possible, but you have to be careful to avoid the quicksand which surrounds this style. It doesn't appear to scale up to larger programs as well as the JFrame subclass style. If you start to need static variables, other than constants, you're starting to sink, and it's time to make some different design decisions. Take a look at Commentary - Build window in main() for an example of how to do this.

JPanel subclass. Basing your GUI on a subclass of JPanel which is used for the content pane is one approach. I've used this occasionally, but have gone back to subclassing JFrame. If you use it, you'll probably end up writing a method in the JPanel subclass to build menus. It's not bad, but is more awkward.

Other sites