Overview of AWT and Swing

The Java Foundation Classes (JFC) provide two frameworks for building GUI based applications. The Abstract Windowing Toolkit (AWT) relies on the underlying windowing system to presents its GUI components. The other toolkit in the JFC called Swing implements a set of lightweight GUI components written in Java that are not dependent on the underlying windowing system. Both AWT and Swing rely on the same event handling model. We will be using mostly the classes from Swing to develop our graphical user interfaces.

To start with, you need a basic window. It is called JFrame in Swing. This is the inheritance view of JFrame. The arrow ( -> ) indicates "inherits from".

JFrame -> Frame -> Window -> Container -> Component -> Object.

JFrames can have the same "look and feel" of the native windowing framework. In other words your graphical user interface on a Macintosh will look like a Macintosh window and so on. The JFrame by itself is not enough. You need something to draw on or add components to. That functionality is provided by the class JPanel. JPanel acts like the canvas for a frame. The hierarchy for JPanel is as follows:

JPanel -> JComponent -> Container -> Component -> Object.

To draw on the canvas or JPanel you must be familiar with these three things:

repaint() method is called if something has changed and you want to redraw the canvas. You can just redraw a portion of the canvas if you send a bounding box giving the coordinates of the region that needs to be redrawn.

paintComponent() method is called in response to the repaint() method. Moreover, paintComponent() is called if your window gets resized or moved.

Graphics object g is a parameter to the paintComponent() method. It is a collection of attributes. You can think of it as a pen that can write text, draw lines or fill in shapes.

Graphics

The abstract class java.awt.Graphics provides a device independent interface for rendering graphics. When drawing on AWT components, you override the paint() method. When drawing on Swing components you override the paintComponent() method.
public class DrawingPanel extends JPanel {
  public void paintComponent (Graphics g) {
    g.setColor (Color.black);
    g.drawString ("Hello World!", 10, 50);
  }
  public static void main (String args[]) {
    JFrame frame = new JFrame ("Drawing Panel");
    DrawingPanel panel = new DrawingPanel();
    frame.getContentPane().add(panel);
    frame.setSize (200, 100);
    frame.setVisible (true);
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
  }
}

Graphics Coordinate System

The graphics context uses a simple coordinate system in which each pixel is represented by its x and y coordinates. The origin of the coordinate system is located at the top left corner of the component. The x coordinate increases from left to right and the y coordinate increases from top to bottom.

Component Color and Graphics Color

Every component has two colors associated with it: a foreground and a background color. You set the colors by calling:
public void setBackground (Color c);
public void setForeground (Color c);

You can think of the graphics object as having a pen for drawing and a paintbrush for painting. When you use the g.setColor() method you set the color of both the pen and the paintbrush. Drawing refers to making a line drawing and is usually done by calling methods of the form drawX(). Painting refers to filling a bounded object with color. Methods of the form fillX() are for painting.

Color Class

Colors are created from an RGB value which is a collection of three numbers that specify the amount of red, green, and blue that are mixed together to form the color. The Color class has three constructors:
public Color (int r, int g, int b);       // range in values 0 to 255
public Color (int rgb);		          // rgb = 65536 * r + 256 * g + b
public Color (float r, float g, float b); // range in values 0.0 to 1.0

In theory it is possible to specify 256 x 256 x 256 = 16,777,216 different colors but in practice the actual colors that can be displayed depends on the quality of your system's monitor. There are 13 predefined colors - black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, and yellow.

The brighter() and darker() methods enable you to start with a standard color and lighten or darken it.

Color red = Color.red;	
Color brightRed = red.brighter();
Color darkRed = red.darker();

The RGB mixture (255, 255, 255) can be used to create pure white, while (0, 0, 0) is used to specify black. Shades of gray are colors whose RGB components have equal values. Thus (128, 128, 128) is the specification for Color.gray.

Rendering Text

Each graphics context has an associated Font and FontMetrics object and the Graphics class provides the following methods to access them:
Font getFont();		void setFont (Font f)
Font getFontMetrics();	

The Font class defines a constructor that can be used to obtain available fonts:

Font (String name, int style, int size)
Some common fonts are - Serif, SansSerif, Monospaced, Dialog, DialogInput, etc. To get all the fonts available on your system run the following piece of code:
GraphicsEnvironment ge = GrahpicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();

Supported styles include PLAIN, BOLD, ITALIC, BOLD+ITALIC. The Font() constructor is designed to work with any set of arguments. If you input the name of a font that is not available the system will supply a default font.

The FontMetrics is an object that encapsulates important data about a font such as its height and width.

Text rendering in a component is done using the following methods. The string is drawn with the baseline of the first character at the specified coordinates, using the current font and color.

void drawString (String str, int x, int y)

Drawing Lines

The Graphics class provides the following method for drawing lines. The line is drawn from point (x1, y1) to point (x2, y2) using the current color.
void drawLine ( int x1, int y1, int x2, int y2)

Drawing Rectangles

The Graphics class provides methods for drawing the outlines of rectangles. Methods are also provided to fill the rectangles with the current color. The rectangle is specified by giving the coordinates of the top left corner, the width, and the height.
void drawRect (int x, int y, int width, int height)
void fillRect (int x, int y, int width, int height)
void drawRoundRect (int x, int y, int width, int height, int arcWidth, 
		    int arcHeight)
The parameters arcWidth and arcHeight specify the horizontal and vertical diameters of the arc at the four corners.
void draw3DRect (int x, int y, int width, int height,
			int arcWidth, int arcHeight, boolean raised)
The edges of the rectangle will be highlighted so that it appears as if the edges were beveled and lit from the upper left corner. The raised argument determines whether the rectangle appears to be raised above or sunk into the drawing surface.

Drawing Ovals

The Graphics class provides a method for drawing ovals (ellipses or circles). A method is provided to fill the oval with the current color. The oval is bounded by an invisible rectangle.
void drawOval (int x, int y,			// top left corner
		  int width, int height)
void fillOval (int x, int y, int width, int height)

Drawing Arcs

The Graphics class provides a method for drawing arcs. These arcs can be circular or elliptical. The starting point of the arc is given by a starting angle, and the ending point is given by the angle swept by the arc. Angles are measured in degrees. Positive angles are measured counter clockwise. The arc is bounded by a rectangle. The center of the arc coincides with the center of the bounding rectangle. A method is also provided to fill the area bounded by the arc and its two radii with the current color, resulting in a pie segment.
void drawArc (int x, int y,			// top left corner
		int width, int height,		// bounding rectangle
		int startAngle, int arcAngle)
void fillArc (int x, int y, int width, int height, 
	      int startAngle, int arcAngle)

Drawing Polygons

A polygon is a closed sequence of line segments. Given a sequence of points (called vertices), line segments connect one vertex to the next in the sequence, finishing with the last vertex being connected with the first one. The Polygon class has the following constructor
Polygon (int[] xpoints, int[] ypoints, int npoints)

The Graphics class provides the following methods for drawing polygons. The outline of the polygon is drawn or filled with the current color.

void drawPolygon (int[] xPoints, int[] yPoints, int nPoint)
void drawPolygon (Polygon p)
void fillPolygon (int[] xPoints, int[] yPoints, int nPoints)
void fillPolygon (Polygon p)

A polyline is an open figure, similar to a polygon, where the last vertex is not connected to the first one.

void drawPolyline (int[] xPoints, int[] yPoints, int nPoints)

Clipping

A Graphics object maintains a clip region. The clip region of a graphics context defines the area in which all drawing will be done. In other words, the clip region defines the actual drawing area used for rendering operations. The region can be all or part of the associated component. Rendering operations have no effect outside the clip region.
void setClip (int x, int y, int width, int height)