Simple graphics in Java

There are four classes/interfaces that we can use to do real graphics (meaning, drawing shapes and lines) in Java:

PaintPanel

A PaintPanel is a window component, just like JLabel or JButton. It can be added to a window. It is simply an area where the shapes will appear. The methods that we’ll be concerned with are

Painter

This interface contains one method, void paint(Graphics g). Objects of classes that implement this interface are attached to a PaintPanel. When the paint() method is called, the Painter draws shapes and lines on the paint panel by calling appropriate methods on the Graphics object, more on that below.

Whenever we want the panel to be drawn, we will call repaint() on the PaintPanel. That automatically calls the attached Painter’s method paint() with the appropriate Graphics object.

The panel’s repaint() method is also automatically called whenever the panel needs to be drawn; for example, when it is made visible for the first time, when it is shown after being minimized, or when it is uncovered by a window that hid all or part of it.

Graphics

An instance of Graphics controls the drawing of a certain GUI component; in our examples it will always be a PaintPanel. When the following methods are called on the Graphics object, then lines, shapes, etc, appear on the PaintPanel. Coordinates act like coordinates in the first quadrant of the plane, except that the origin is in the upper lefthand corner, not the lower lefthand corner.

Polygon

This class is used to represent a polygon which can be passed to the fillPolygon() method. We’ll only need the constructor:

Polygon(int[] xpoints, int[] ypoints, int npoints)