COLOR CHOOSERS
JColorChooser is a Swing class that you use to select a color.
It typically pops up a window with a color chooser dialog in it.
You choose a color (like blue or red), and the window goes away.
The result of this process is an instance of the java.awt.Color
class. A good context for JColorChooser is a word processor,
where you're specifying the color to use for highlighted text.
You have three ways of selecting or entering a color with
JColorChooser. You can choose a color swatch, a small square of
a particular color. There's also RGB (red/green/blue) and HSB
(hue/saturation/brightness) available; these represent a color
using numerical values. For example, if you enter the values
(255, 0, 255), you get the color magenta. You can also specify
an initial color to a JColorChooser object.
JColorChooser is typically used as a pop-up modal dialog. However
you can also use it as an always visible component; in this case,
you are notified of color changes via event listeners. Here's an
example of using JColorChooser in this latter way:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.colorchooser.*;
import javax.swing.event.*;
public class ColorChoose {
public static void main(String args[]) {
final JFrame frame = new JFrame("Color Chooser Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// set up the canvas to draw on
final Canvas canv = new Canvas();
canv.setSize(new Dimension(300, 300));
// set up the color chooser and its listener
final JColorChooser jcc = new JColorChooser(Color.blue);
final ColorSelectionModel csm = jcc.getSelectionModel();
csm.addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
// retrieve the current color and draw
Color c = csm.getSelectedColor();
Graphics g = canv.getGraphics();
g.setColor(c);
g.fillOval(150, 150, 100, 100);
}
}
);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add("North", jcc);
panel.add("South", canv);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
The program sets up two regions. The upper region contains a color
chooser that is set to an initial color of blue. In the lower
region, a Canvas object is used to draw graphical objects.
Choose a color in the upper area, and the program displays
a filled oval of that color in the lower area.
Actual color changes in the JColorChooser are abstracted through
a ColorSelectionModel. This is an interface that supports methods
for getting and setting colors, and tracking color change. Notice
that the program adds a change listener to the model. The change
listener tracks changes to the current color. When a color changes,
the change listener calls stateChanged to retrieve the color and
draw a graphical object in the new color.
|