The user can use the Effects menu's Select Color… menu item to set the drawing color used for all drawing operations. When the user selects a drawing color, figures are drawn using that color, even if the user is drawing freehand with the mouse. Solid fills are drawn with that color, and gradient fills are drawn starting with that color and shading off to black. Even text is drawn in the color the user selects. To let the user select a drawing color, Painter uses a Swing JColorChooser dialog box. This dialog box is easy to put to work, and it has a great deal of utility. Here's all you need to do: Use the JColorChooser class's static showDialog method and store the returned color; Painter stores that value in a Color object named color. Here's how it displays the color chooser (setting the default color to black) and stores the selected color: if(e.getSource() == colorMenuItem){ color = JColorChooser.showDialog(this, "Select your color", Color.black); start.x = -20; start.y = -20; end.x = -20; end.y = -20; } You can see the color chooser in Figure 4.8. As you can tell, there's a lot of functionality in that dialog box. Figure 4.8. Selecting a color.You can see the significant methods of the JColorChooser class in Table 4.4.
In the paint method, where the actual drawing is done, Painter installs color as the new drawing color (and uses black as a default drawing color if no other color was selected): if(color != null){ gImage.setColor(color); } else { gImage.setColor(new Color(0, 0, 0)); } And that completes the Painter applicationeverything's all packed into the code now, and it's ready to roll. NOTE Download the complete source code for the Painter applicationPainter.java and tile.jpgat the Sams website. You can run Painter as you have the previous projectsjust compile and run it using Java. Make sure that tile.jpg (which comes in the download) is in the same directory as Painter.class when you run Painter. |