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 aJDialog
backCall 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.
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 ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.