Colors and graphics Primitives
You may be wondering how color comes into play when drawing graphics primitives.
The drawRect() method uses the color attribute of the Graphics object to determine the color of the rectangle. The color attribute is also used with the fillRect() method, which draws a filled rectangle.
The background color attribute is used to clear a rectangle using the clearRect() method. The color and background color attributes similarly impact other graphics primitives operations such as the fillOval() method.
You already know how to create different geometric primitives and more complicated shapes. This lesson teaches how to add some color and fancy outlines to your graphics and represents filling and stroking:
- Filling is a process of painting the shape's interior with solid color or a color gradient, or a texture pattern
- Stroking is a process of drawing a shape's outline applying stroke width, line style, and color attribute
To apply fancy line styles and fill patterns to geometric primitives change the stroke and paint attributes in the Graphics2D context before rendering.
For example, draw a dashed line by creating an appropriate Stroke object. To add this stroke to the Graphics2D context before you render the line call the setStroke method.
Similarly, you apply a gradient fill to a Shape object by creating a GradientPaint object and adding it to the Graphics2D context.
The following code lines enrich geometric primitives with filling and stroking context:
// draw RoundRectangle2D.Double
final static float dash1[] = {10.0f};
final static BasicStroke dashed = new BasicStroke(1.0f,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
g2.setStroke(dashed);
g2.draw(new RoundRectangle2D.Double(x, y, rectWidth, rectHeight, 10, 10));
// fill Ellipse2D.Double
redtowhite = new GradientPaint(0,0,color.RED,100, 0,color.WHITE);
g2.setPaint(redtowhite);
g2.fill (new Ellipse2D.Double(0, 0, 100, 50));