Graphics in Java - 1. Overview

Java graphics are, unfortunately, complicated, and like most of Java, there is more than one way of doing something. In this course we will be learning to use SWING for making GUIs and drawing graphics.

There are two types of Java graphics programs:

  1. Applications. These are the types of program which we have been writing so far. They must have a main() function to run. All application graphics programs either extend a JFrame (or Frame) class, or create a JFrame (or Frame)
  2. Applets. These are program which are embedded in a webpage and run in a browser. They must have an init() and a paint(Graphics g) function to run. The actual graphics objects are the same, but applets run differently – without a main() function. All applets extend the class Applet. (For Swing, change Applet to JApplet and paint() to paintComponent() .)

There are two three+ sets of Java graphics classes (packages)

  1. AWT. This is the older and more complete set of graphics classes. It relies on the base operating system to draw the graphics. Thus your GUI will look different on a Mac and on a PC
  2. SWING.

    This is the "newer" graphics package. It does all of the drawing itself, so your application will look the same on every operating system. It may be a bit slower because of this though.
    Swing is built on top of AWT and still uses a lot of AWT stuff – e.g. the AWT Color class. It hasn't replaced everything, mostly just the buttons, labels, etc. that you place on the screen. All of the Swing objects start with a J. For example "Button" is an AWT object, but "JButton" is Swing.

    Swing normally looks better than AWT, but some of it is stupidly complex. Don't ever put AWT objects onto a Swing one if there is a Swing object that does the same thing. Why not? Strange things happen and your program may not work properly. For example, adding Label to a JPanel is bad because you should use JLabel. Two of the most common mistakes (based on comments on the internet are):

  3. JavaFX. JavaFX is the newest Java GUI system. It is totally independent of Swing (and AWT). However, it is possibly to combine Swing and JavaFX in a program. Update: while Oracle claims that JavaFX will be replacing Swing, it's not really clear on how much it is developing and pushing JAvaFX.
  4. SWT There is also something called SWT. It is the same level at Swing, but is designed to replace both Swing and AWT. If you're going to learn something beyond Swing, I would recommend JavaFX.

Comparison of Swing vs JavaFX

Pie Chart in SWINGPie Chart in JavaFX
Swing Source codeJavaFX Source Code

Diagrams (which may or may not be useful)

Types of objects: Containers vs Components
Containers can be inside other containers: e.g. two JPanels inside another JPanel inside a JFrame

Hierarchy of AWT classes (partial)

Hierarchy of Swing classes (partial)

Hierarchy of Swing classes (not up to date)