HTML Markup | JavaScript | Java | Home & Links

Tutorial 16 - Graphics and Imaging

Graphics brings life to applications. Java allows creation and modification of images using both awt and the newer JFC 2D architecture. Artists tend to think in terms of a canvas as the foundation for their images and graphics. Swing (JPanel and JFrame) and awt (Canvas) objects can be extended for use as the basic canvas. Java applets and applications tie the canvas to the window frame. Output to the canvas takes place through a graphics context encapsulated by the Graphics class. This tutorial introduces some fundamental concepts of graphics and imaging.

The Canvas

The canvas origin (0,0) is set at the upper left corner position of its container. The graphics context is passed when the paint() or update() method is called. Use either setSize(x,y) or setBounds(x,y,w,h) to set the canvas dimensions. Use the getGraphics() method of the Component object to get the context.

Shapes and Paths

2D shapes are contained in the awt.geom library which must be imported. The paint() method must be overridden and its Graphics object cast to a Graphics2D object. Objects are first defined with one of the following 2D constructors and then drawn with either draw(obj) [outlined shape] or fill(obj) [filled shape].

Antialiasing provides cleaner graphics and text rendition. To turn antialiasing on use: setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

Shape awtJFC 2D
  • Line
  • Rectangle
  • (rounded)
  • Ellipse
  • Arc
  • Polygon
  • drawLine(x1,y1,x2,y2)
  • drawRect(x1,y1,x2,y2)
  • drawRoundRect(x1,y1,x2,y2,r1,r2)
  • drawOval(x,y,w,h)
  • drawArc(x,y,w,h,sdeg,ndeg)
  • drawPolygon(x[],y[],numPoints)
  • Line2D.Float(x1,y1,x2,y2)
  • Rectangle2D.Float(x1,y1,x2,y2)
  • RoundedRectangle2D.Float(x1,y1,x2,y2)
  • Ellipse2D.Float(x,y,w,h)
  • Arc2D.Float(x,y,w,h,sdeg,ndeg,clos)

2D polygons are represented by paths or series of line segments that enclose the polygon. A GeneralPath object is created and the start point set with the moveTo(x,y) method. The line segments are defined with lineTo(x,y). The polygon is then completed with ClosePath().

2D arcs are built starting with an elliptical shape, then clipped by using a start angle and degree of rotation (think compass or clock). The final parameter defines closure using one of the Arc2D constants OPEN, CHORD or PIE.

Styles and Patterns

Pen strokes control the width, endpoint and junction renderings of drawn lines. A pen nib (ie. stroke style) is constructed with BasicStroke(width,endCap,joint). Width is in pixels expressed with type float. endCap and joint are optional parameters for decorative features. The BasicStroke class has special constants for these parameters. A pen nib is changed with setStroke(nib).

Fill patterns control how a drawn object is filled in with ink. Color, gradients and textures are the common fill patterns used. A gradient fill is a gradual change of color between points. It can be acyclic (default) or cyclic (ie. repeating). Two color gradient patterns are constructed with GradientPaint(x1,y1,c1,x2,y2,c2) . Adding a parameter of true will make the pattern cyclic. Multiple color patterns use the LinearGradientPaint class. Texture patterns are constructed with TexturePaint(bufferedImage, shape). Inkwells are filled with setPaint(patternOrColor) or setColor(color).

Project: Checkerboard Tilings

Create an applet that draws a checkerboard in black and white. Use parameters for tile dimensions and the number of tiles in each direction.

Extension #1: Randomly choose from list of color pairs.

Extension #2: Cycle through a list of color pairs. (found in is an application demo that can easily be converted into an applet.


Affine Transforms offer complex geometric control over shapes such as translation, rotation, scaling and shearing.

Clipping can be applied to any canvas, including outlined text. setClip(shape) and clip(appendedShape) are the appropriate methods.

Using Images

Create images with img=canvasObj.createImage(iwidth,iheight);.
Load images with File("fileName"));.
Warning: Use try/catch trapping techniques as exception errors can occur.
Display images with drawImage(imgObj,x,y,this).
Other useful Graphics methods are getWidth(), getHeight() and getType(). (found in is a simple applet that displays an image.

The Applet class getImage() method can also be used for fetching images.

Image img=getImage(new URL(""));
//fetches image from absolute path
Image img1=getImage(getDocumentBase(),"image.gif");
//fetches image from the html folder
Image img2=getImage(getCodeBase(),"image.gif");
//fetches image from the applet folder

Adding Text

Font and FontMetrics classes allow selection of different typefaces and sizes as well as providing information on the geometry of the type. The TextLayout class can be used to add simple textual messages to graphics. The method getOutline(transformHandle) returns an outline of the text as a shape. This can then be displayed with draw(shapevar). The method drawString() is used to write simple text to the canvas.

The following is a simple awt Hello Graphics World application that demonstrates how to use JFC 2D objects for text display. Included are gradient text, textured text and outlined text.

Adding Drop Shadows provides a great demo of drop shadows (with source code) with variable opacity.

JR's HomePage | Comments [jatutorg.htm:2012 06 12]