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

Filling Shapes

Iguana fills its shapes with a number of colors, using the setPaint() method of Graphics2D. This method sets the current color in the graphics context, so we set it to a different color before each drawing operation. setPaint() accepts any object that implements the Paint interface. The 2D API includes three implementations of this interface, representing solid colors, color gradients, and textures.

Solid Colors

The java.awt.Color class represents color in Java. A Color object describes a single color and implements the Paint interface for filling an area with it. You can create an arbitrary Color by specifying the red, green, and blue values, either as integers between 0 and 255 or as floating-point values between 0.0 and 1.0. The (somewhat strange) getColor() method can be used to look up a named color in the system properties table, as described in Chapter 11.

The Color class also defines a number of static final color values; we used these in the Iguana example. These constants, such as Color.black and Color.red, provide a convenient set of basic color objects for your drawings.

Tip

Excessive creation of redundant color instances is a common cause of memory bloat in Java clients. Consider using a factory pattern to ensure you don’t have 200 instances of periwinkle.

Color Gradients

A color gradient is a smooth blend between two or more colors. The GradientPaint class encapsulates this idea in a handy implementation of the Paint interface. All you need to do is specify ...

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