Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

A Quick Tour of Java 2D

Next we’ll embark on a quick tour of Java 2D, including working with shapes and text. We’ll finish with an example of Java 2D in action.

Filling Shapes

The simplest path through the rendering pipeline is filling shapes. For example, the following code creates an ellipse and fills it with a solid color. (This code would live inside a paint() method somewhere. We’ll present a complete, ready-to-run example a little later.)

    Shape c = new Ellipse2D.Float(50, 25, 150, 150); // x,y,width,height
    g2.setPaint(Color.blue);
    g2.fill(c);

Here, g2 is our Graphics2D object. The Ellipse2D shape class is abstract, but is implemented by concrete inner subclasses called Float and Double that work with float or double precision, respectively. The Rectangle2D class, similarly, has concrete subclasses Rectangle2D.Float and Rectangle2D.Double.

In the call to setPaint(), we tell Graphics2D to use a solid color, blue, for all subsequent filling operations. Next, the call to fill() tells Graphics2D to fill the given shape.

All geometric shapes in the 2D API are represented by implementations of the java.awt.geom.Shape interface. This interface defines methods that are common to all shapes, like returning a rectangle bounding box or testing if a point is inside the shape. The java.awt.geom package is a smorgasbord of useful shape classes, including Rectangle2D, RoundRectangle2D (a rectangle with rounded corners), Arc2D, Ellipse2D, and others. In addition, a few more basic classes in

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content