Home > Articles > Programming > Java

Java 2D: Graphics in Java 2

Larry Brown and Marty Hall teach you how to: draw 2D shapes, tile an image inside a shape, use local fonts, custom pen settings, change the opaqueness of objects, and translate and rotate coordinate systems.
This sample chapter is excerpted from Core Web Programming, by Larry Brown and Marty Hall.
This chapter is from the book

This chapter is from the book

Anyone who has even lightly ventured into developing detailed graphical pro

Java 2D is probably the second most significant addition to the Java 2 Platform, surpassed only by the Swing GUI components. The Java 2D API provides a robust package of drawing and imaging tools to develop elegant, professional, high-quality graphics. The following important Java 2D capabilities are covered in this chapter:

  • Colors and patterns: graphics can be painted with color gradients and fill patterns.

  • Transparent drawing: opaqueness of a shape is controlled through an alpha transparency value.

  • Local fonts: all local fonts on the platform are available for drawing text.

  • Explicit control of the drawing pen: thickness of lines, dashing patterns, and segment connection styles are available.

  • Transformations of the coordinate system—translations, scaling, rotations, and shearing—are available.

These exciting capabilities come at a price—the Java 2D API is part of the Java Foundation Classes introduced in Java 2. Thus, unlike Swing, which can be added to the JDK 1.1, you cannot simply add Java 2D to the JDK 1.1. The Java Runtime Environment (JRE) for the Java 2 Platform is required for execution of 2D graphical applications, and a Java 2-capable browser or the Java Plug-In, covered in Section 9.9 (The Java Plug-In), is required for execution of 2D graphical applets. Complete documentation of the Java 2D API, along with additional developer information, is located at http://java.sun.com/products/java-media/2D/. Also, the JDK 1.3 includes a 2D demonstration program located in the installation directory: root/jdk1.3/demo/jfc/Java2D/. In addition, Java 2D also supports high-quality printing; this topic is covered in Chapter 15 (Advanced Swing).

10.1 Getting Started with Java 2D

In Java 2, the paintComponent method is supplied with a Graphics2D object, which contains a much richer set of drawing operations than the AWT Graphics object. However, to maintain compatibility with Swing as used in Java 1.1, the declared type of the paintComponent argument is Graphics (Graphics2D inherits from Graphics), so you must first cast the Graphics object to a Graphics2D object before drawing. Technically, in Java 2, all methods that receive a Graphics object (paint, paintComponent, get_Graphics) actually receive a Graphics2D object.

The traditional approach for performing graphical drawing in Java 1.1 is reviewed in Listing 10.1. Here, every AWT Component defines a paint method that is passed a Graphics object (from the update method) on which to perform drawing. In contrast, Listing 10.2 illustrates the basic approach for drawing in Java 2D. All Swing components call paintComponent to perform drawing. Technically, you can use the Graphics2D object in the AWT paint method; however, the Graphics2D class is included only with the Java Foundations Classes, so the best course is to simply perform drawing on a Swing component, for example, a JPanel. Possible exceptions would include direct 2D drawing in the paint method of a JFrame, JApplet, or JWindow, since these are heavyweight Swing components without a paintComponent method.

Listing 10.1 Drawing graphics in Java 1.1

public void paint(Graphics g) {
 // Set pen parameters

 // Draw a shape
 g.drawRect(...);   // outline
 g.fillRect(...);   // solid
 g.drawPolygon(...); // outline
 g.fillPolygon(...); // solid
 g.drawOval(...);   // outline
 g.fillOval(...);   // solid

Listing 10.2 Drawing graphics in the Java 2 Platform

public void paintComponent(Graphics g) {
 // Clear background if opaque
 // Cast Graphics to Graphics2D
 Graphics2D g2d = (Graphics2D)g;
 // Set pen parameters
 // Allocate a shape 
 SomeShape s = new SomeShape(...);
 // Draw shape
 g2d.draw(s); // outline
 g2d.fill(s); // solid

The general approach for drawing in Java 2D is outlined as follows.

Cast the Graphics object to a Graphics2D object.

Always call the paintComponent method of the superclass first, because the default implementation of Swing components is to call the paint method of the associated ComponentUI; this approach maintains the component look and feel. In addition, the default paintComponent method clears the off-screen pixmap because Swing components implement double buffering. Next, cast the Grap_hics object to a Graphics2D object for Java 2D drawing.

public void paintComponent(Graphics g) {
 Graphics2D g2d = (Graphics2D)g;

Core Approach

When overriding the paintComponent method of a Swing component, always call super.paintComponent.

Modify drawing parameters (optional).

Drawing parameters are applied to the Graphics2D object, not to the Shape object. Changes to the graphics context (Graphics2D) apply to every subsequent drawing of a Shape.

Create a Shape object.
Rectangle2D.Double rect = ...;
Ellipse2D.Double ellipse = ...;
Polygon poly = ...;
GeneralPath path = ...;
// Satisfies Shape interface
SomeShapeYouDefined shape = ...; 
Draw an outlined or filled version of the Shape.

Pass in the Shape object to either the draw or fill method of the Graphics2D object. The graphic context (any paint, stroke, or transform applied to the Graphics2D object) will define exactly how the shape is drawn or filled.


The Graphics2D class extends the Graphics class and therefore inherits all the familiar AWT graphic methods covered in Section 9.11 (Graphics Operations). The Graphics2D class adds considerable functionality to drawing capabilities. Methods that affect the appearance or transformation of a Shape are applied to the Graphics2D object. Once the graphics context is set, all subsequent Shapes that are drawn will undergo the same set of drawing rules. Keep in mind that the methods that alter the coordinate system (rotate, translate, scale) are cumulative.

Useful Graphics2D Methods

The more common methods of the Graphics2D class are summarized below.

public void draw(Shape shape)

This method draws an outline of the shape, based on the current settings of the Graphics2D context. By default, a shape is bound by a Rectangle with the upper-left corner positioned at (0,0). To position a shape elsewhere, first apply a transformation to the Graphics2D context: rotate, transform, tra_nslate.

    public boolean drawImage(BufferedImage image,
               BufferedImageOp filter,
		                   int left, int top)

This method draws the BufferedImage with the upper-left corner located at (left, top). A filter can be applied to the image. See Section 10.3 (Paint Styles) for details on using a BufferedImage.

public void drawString(String s, float left, float bottom)

The method draws a string in the bottom-left corner of the specified location, where the location is specified in floating-point units. The Java 2D API does not provide an overloaded drawString method that supports double arguments. Thus, the method call drawString(s, 2.0, 3.0) will not compile. Correcting the error requires explicit statement of floating-point, literal arguments, as in drawString(s, 2.0f, 3.0f).

Java 2D supports fractional coordinates to permit proper scaling and transformations of the coordinate system. Java 2D objects live in the User Coordinate Space where the axes are defined by floating-point units. When the graphics are rendered on the screen or a printer, the User Coordinate Space is transformed to the Device Coordinate Space. The transformation maps 72 User Coordinate Space units to one physical inch on the output device. Thus, before the graphics are rendered on the physical device, fractional values are converted to their nearest integral values.

public void fill(Shape shape)

This method draws a solid version of the shape, based on the current settings of the Graphics2D context. See the draw method for details of positioning.

public void rotate(double theta)

This method applies a rotation of theta radians to the Graphics2D transformation. The point of rotation is about (x, y)=(0, 0). This rotation is added to any existing rotations of the Graphics2D context. See Section 10.7 (Coordinate Transformations).

public void rotate(double theta, double x, double y)

This method also applies a rotation of theta radians to the Graphics2D transformation. However, the point of rotation is about (x, y). See Section 10.7 (Coordinate Transformations) for details.

public void scale(double xscale, yscale)

This method applies a linear scaling to the x- and y-axis. Values greater than 1.0 expand the axis, and values less than 1.0 shrink the axis. A value of -1 for xscale results in a mirror image reflected across the x-axis. A yscale value of -1 results in a reflection about the y-axis.

public void setComposite(Composite rule)

This method specifies how the pixels of a new shape are combined with the existing background pixels. You can specify a custom composition rule or apply one of the predefined AlphaComposite rules: AlphaComposite.Clear, AlphaComposite.DstIn, AlphaCompos_ite.DstOut, AlphaComposite.DstOver, AlphaCompos_ite.Src, AlphaComposite.SrcIn, AlphaCompos_ite.SrcOut, AlphaComposite.ScrOver.

To create a custom AlphaComposite rule, call getInstance as in



int type = AlphaComposite.SRC_OVER;
float alpha = 0.75f;
AlphaComposite rule = 
  AlphaComposite.getInstance(type, alpha);

The second approach permits you to set the alpha value associated with composite rule, which controls the transparency of the shape. By default, the transparency value is 1.0f (opaque). See Section 10.4 (Transparent Drawing) for details. Clarification of the mixing rules is given by T. Porter and T. Duff in "Compositing Digital Images," SIGGRAPH 84, pp. 253–259.

public void setPaint(Paint paint) 

This method sets the painting style of the Graphics2D context. Any style that implements the Paint interface is legal. Existing styles in the Java 2 Platform include a solid Color, a GradientPaint, and a Tex_turePaint.

public void setRenderingHints(Map hints)

This method allows you to control the quality of the 2D drawing. The AWT includes a RenderingHints class that implements the Map interface and provides a rich suite of predefined constants. Quality aspects that can be controlled include antialiasing of shape and text edges, dithering and color rendering on certain displays, interpolation between points in transformations, and fractional text positioning. Typically, antialiasing is turned on, and the image rendering is set to quality, not speed:

RenderingHints hints = new RenderingHints(
hints.add(new RenderingHints(       RenderingHints.KEY_RENDERING, 
public void setStroke(Stroke pen)

The Graphics2D context determines how to draw the outline of a shape, based on the current Stroke. This method sets the drawing Stroke to the behavior defined by pen. A user-defined pen must implement the Stroke interface. The AWT includes a BasicStroke class to define the end styles of a line segment, to specify the joining styles of line segments, and to create dashing patterns. See Section 10.6 (Stroke Styles) for details.

public void transform(AffineTransform matrix)

This method applies the Affine transformation, matrix, to the existing transformation of the Graphics2D context. The Affine transformation can include both a translation and a rotation. See Section 10.7 (Coordinate Transformations).

public void translate(double x, double y)

This method translates the origin by (x, y) units. This translation is added to any prior translations of the Graphics2D context. The units passed to the drawing primitives initially represent 1/72nd of an inch, which on a monitor, amounts to one pixel. However, on a printer, one unit might map to 4 or 9 pixels (300 dpi or 600 dpi).

public void setPaintMode()

This method overrides the setPaintMode method of the Graphics object. This implementation also sets the drawing mode back to "normal" (vs. XOR) mode. However, when applied to a Graphics2D object, this method is equivalent to setComposite(AlphaComposite.SrcOver), which places the source shape on top of the destination (background) when drawn.

public void setXORMode(Color color)

This method overrides the setXORMode for the Graphics object. For a Graphics2D object, the setXORMode method defines a new compositing rule that is outside the eight predefined Porter-Duff alpha compositing rules (see S_ection 10.4). The XOR compositing rule does not account for transparency (alpha) values and is calculated by a bitwise XORing of the source color, destination color, and the passed-in XOR color. Using XOR twice in a row when you are drawing a shape will return the shape to the original color. The transparency (alpha) value is ignored under this mode, and the shape will always be opaque. In addition, antialiasing of shape edges is not supported under XOR mode.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020