CONTENTS | PREV | NEXT | Java 2D API |
Graphics2D provides rendering methods for Shapes, Text, and Images:
To stroke and fill a shape, you must call both the draw and fill methods.Graphics2D also supports the draw and fill methods from previous versions of the JDK software, such as drawOval and fillRect.
The outline of any Shape can be rendered with the Graphics2D.draw method. The draw methods from previous versions of the JDK software are also supported: drawLine, drawRect, drawRoundRect, drawOv al, drawArc, drawPolyline, drawPolygon, draw3DRect.When a Shape is drawn, its path is stroked with the Stroke object in the Graphics2D context. (See "Stroke Attributes" for more information.) By setting an approp riate BasicStroke object in the Graphics2D context, you can draw lines of any width or pattern. The BasicStroke object also defines the line's endcap and join attributes.
In the following example, a GeneralPath object is used to define a star and a BasicStroke object is added to the Graphics2D context to define the star's line with and join attributes.
public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; // create and set the stroke g2.setStroke(new BasicStroke(4.0f)); // Create a star using a general path object GeneralPath p = new GeneralPath(GeneralPath.NON_ZERO); p.moveTo(- 100.0f, - 25.0f); p.lineTo(+ 100.0f, - 25.0f); p.lineTo(- 50.0f, + 100.0f); p.lineTo(+ 0.0f, - 100.0f); p.lineTo(+ 50.0f, + 100.0f); p.closePath(); // translate origin towards center of canvas g2.translate(100.0f, 100.0f); // render the star's path g2.draw(p); }
The Graphics2D.fill method can be used to fill any Shape. When a Shape is filled, the area within its path is rendered with the Graphics2D context's current Paint attribute--aColor, TexturePaint, or GradientPaint. The fill methods from previous versions of the JDK software are also supported: fillRect, fill3DRect, fillRoundRect, fillOval, fillArc, fillPolygon, clearRect.
In the following example, setColor is called to define a green fill for a Rectangle2D.
public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setPaint(Color.green); Rectangle2D r2 = new Rectangle2D.Float(25,25,150,150); g2.fill(r2); }
To render a text string, you call Graphics2D.drawString, passing in the string that you want to render. For more information about rendering text and selecting fonts, see "Fonts and Text Layout" .
To render an Image, you create the Image and call Graphics2D.drawImage. For more information about processing and rendering images, see "Imaging".