Java Reference
In-Depth Information
seen to draw the image. For the custom color menu item icon, you just want a color rectangle on the image
that is the custom color. You could produce this with the following statements:
BufferedImage image = (BufferedImage)(CUSTOM16.getImage());
Graphics2D g2D = image.createGraphics();
g2D.setPaint(color);
g2D.fillRect(3,3,10,10); // Fill 10x10 rectangle
g2D.dispose();
These obtain the underlying image from the
CUSTOM16 ImageIcon
object by calling its
getImage()
method. You cast the reference to its original type,
BufferedImage
, so you can call its
createGraphics()
method. You use the
Graphics2D
object to set the paint color to
color
, and to draw a filled rectangle in
that color on the image using the
fillRect()
method. The image is 16 ×16 pixels, so in the 10 ×10 filled
area you draw a 10 ×10 pixel rectangle with the top-left corner at (3,3). Thus the rectangle is inset from the
boundaries of the image by 3 pixels all round.
For the custom color toolbar button, you should draw a larger filled rectangle because the button icon is
larger than the menu item icon, but other than that the code for the rectangle is similar to the previous frag-
ment. It would be a good idea to distinguish it in some way from the other color toolbar buttons, and one
way of doing this is to draw text on it. This isn't difficult because you can draw text using a
Graphics2D
object.
Using a JColorChooser Dialog
A
JColorChooser
object is a pane for choosing colors. You can add color chooser panes to your own win-
dow to provide a color choosing mechanism, but the class also provides static methods for creating a com-
plete dialog for choosing a color. This is the route you will follow.
The static
createDialog()
method in the
JColorChooser
class returns a
JDialog
object containing a
JColorChooser
pane that you create using a
JColorChooser
constructor and pass to the method. The meth-
od requires six arguments:
• The parent component for the dialog.
• A
String
object specifying the contents of the dialog's title bar.
• A
boolean
value that is
true
when you want a modal dialog and
false
for a modeless dialog.
• A reference to a
JColorChooser
pane.
• An
ActionListener
reference to handle events from the OK button.
• An
ActionListener
reference to handle events from the Cancel button.
The default
JColorChooser
constructor creates a pane with white as the default color. You can also spe-
cify the initial color as an argument to the constructor.
You could construct a color chooser dialog with the following statement:
JDialog chooseColor = JColorChooser.createDialog(
this, "Choose a Custom Color", true,
new JColorChooser(elementColor), this, this);
The statement creates a modal dialog with current window as the parent and as the listener for both dialog
buttons. The default color for the chooser pane in the dialog is
elementColor
.