O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Choosing a Color

Problem

You want to allow the user to select a color from all the colors available on your computer.

Solution

Use Swing’s JColorChooser.

Discussion

OK, so it may be just glitz or a passing fad, but with today’s displays, the 13 original AWT colors are too limiting. Swing’s JColorChooser lets you choose from zillions of colors. From a program’s view, it can be used in three ways:

  • Construct it and place it in a panel

  • Call its ConstructDialog( ) and get a JDialog back

  • Call its showDialog( ) and get back the chosen color

We’ll use the last method, since it’s the simplest and the most likely to be used in a real application. The user has several methods of operating the chooser, too:

Swatches mode

The user can pick from one of a few hundred color variants.

HSB mode

This one’s my favorite. The user picks one of Hue, Saturation, or Brightness to be nailed down; by adjusting another by slider, there is a huge range of different pixel values to choose from, by clicking (or, more fun, dragging) in the central area. See Figure 13-9.

RGB mode

The user picks Red, Green, and Blue components by sliders.

JColorChooser: HSB view in action

Figure 13-9. JColorChooser: HSB view in action

Example 13-5 contains a short program that makes it happen.

Example 13-5. JColorDemo.java

import com.darwinsys.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; /* * Colors - demo of Swing JColorChooser. * Swing's JColorChooser ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required