advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

JavaBoutique : Tutorials :

Java2D: An Introduction and Tutorial

Contents
Introduction
Drawing Shapes
Paint Styles
Transparency
Using Local Fonts
Stroke Styles
Coordinate Transformations
Conclusions

2 Drawing Shapes

2.1 Drawing Shapes: Overview

With the AWT, you generally drew a shape by calling the drawXxx or fillXxx method of the Graphics object. In Java2D, you generally create a Shape object, then call either the draw or fill method of the Graphics2D object, supplying the Shape object as an argument. For example:

public void paintComponent(Graphics g) {
super.paintComponent(g);
  Graphics2D g2d = (Graphics2D)g;
  // Assume x, y, and diameter
  // are instance variables
  Ellipse2D.Double circle = new
    Ellipse2D.double(x, y, diameter, diameter);
  g2d.fill(circle);
  ...
}

You can still call the drawXxx methods if you like, however. This is necessary for drawString and drawImage, and possibly convenient for draw3DRect. Several classes have similar versions that store coordinates as either double precision numbers (Xxx.Double) or single precision numbers (Xxx.Float). The idea is that single precision coordinates might be slightly faster to manipulate on some platforms.

2.2 Shape Classes

Arguments to the Graphics2D draw and fill methods must implement the Shape interface. You can create your own shapes, of course, but following are the major built-in ones:

  • Arc2D.Double, Arc2D.Float
  • Area
  • CubicCurve2D.Double, CubicCurve2D.Float
  • Ellipse2D.Double, Ellipse2D.Float
  • GeneralPath
  • Line2D.Double, Line2D.Float
  • Polygon
  • QuadCurve2D.Double, QuadCurve2D.Float
  • Rectangle2D.Double, Rectangle2D.Float, Rectangle
  • RoundRectangle2D.Double, RoundRectangle2D.Float

2.3 Drawing Shapes: Example Code

Download the source: ShapeExample.java, WindowUtilities.java, and ExitListener.java.

ShapeExample.java

import com.sun.java.swing.*; // For JPanel, etc.
import java.awt.*;           // For Graphics, etc.
import java.awt.geom.*;      // For Ellipse2D, etc.

/** An example of drawing/filling shapes with Java2D in Java 1.2.
 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/
 */

public class ShapeExample extends JPanel {
  private Ellipse2D.Double circle =
    new Ellipse2D.Double(10, 10, 350, 350);
  private Rectangle2D.Double square =
    new Rectangle2D.Double(10, 10, 350, 350);

  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.fill(circle);
    g2d.draw(square);
  }

  // super.paintComponent clears offscreen pixmap,
  // since we're using double buffering by default.

  protected void clear(Graphics g) {
    super.paintComponent(g);
  }

  protected Ellipse2D.Double getCircle() {
    return(circle);
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new ShapeExample(), 380, 400);
  }
}

WindowUtilities.java

import com.sun.java.swing.*;
import java.awt.*;

/** A few utilities that simplify testing of windows in Swing.
 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/
 */

public class WindowUtilities {

  /** A simplified way to see a JPanel or other Container.
   *  Pops up a JFrame with specified Container as the content pane.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title,
                                    Color bgColor) {
    JFrame frame = new JFrame(title);
    frame.setBackground(bgColor);
    content.setBackground(bgColor);
    frame.setSize(width, height);
    frame.setContentPane(content);
    frame.addWindowListener(new ExitListener());
    frame.setVisible(true);
    return(frame);
  }

  /** Uses Color.white as the background color. */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title) {
    return(openInJFrame(content, width, height, title, Color.white));
  }

  /** Uses Color.white as the background color, and the
   *  name of the Container's class as the JFrame title.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height) {
    return(openInJFrame(content, width, height,
                        content.getClass().getName(),
                        Color.white));
  }
}

ExitListener.java

import java.awt.*;
import java.awt.event.*;

/** A listener that you attach to the top-level Frame or JFrame of
 *  your application, so quitting the frame exits the application.
 *  1998 Marty Hall, http://www.apl.jhu.edu/~hall/java/
 */

public class ExitListener extends WindowAdapter {
  public void windowClosing(WindowEvent event) {
    System.exit(0);
  }
}

2.4 Drawing Shapes: Example Output

Output: drawing shapes in Java2D

Next ->


This tutorial was prepared by Marty Hall for work in the Research and Technology Development Center of the Johns Hopkins University Applied Physics Lab, for courses in the Johns Hopkins Part-Time MS Program in Computer Science, and for various industry seminars and courses.

© 1998 Marty Hall.Java 1.2beta4 version.

This article first appeared in November, 1998 and is reprinted with permission of the author.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 34
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

IBM Brings Developers Into the Cloud
Apache at 10: You Can't Buy Us
Microsoft's CodePlex Foundation Moving Forward
Apple Claims 100,000 Apps, Google Analyzes Them
Nokia Latest to Play Opera Mobile 10 Browser
PayPal Opens Up Payment Platform to Devs
Ubuntu Linux 9.10 'Karmic Koala' Starts Its Climb
IBM Links Rational Developer Tools, Tivoli Apps
Libraries Give Vista Apps a Windows 7 Look
Ubuntu: The 'Default Alternative' to Windows?

Delivering Web-based Embedded Fonts in CSS 3
Adobe Helps PHP Developers Create Rich Internet Applications
Java Developers Finding a Home at Adobe Flex
Virtualization Delivers a Dynamic Infrastructure
Consuming XML Web Services in iPhone Applications
Build a More Agile Business with IBM
POJO-Based Solutions for LDAP Access: One Good, One Better
IBM Offers Enhanced Measurement and Management for Energy Usage
IBM Helps Transformation to an Information-Based Enterprise
Top Five Touch UI-Related Design Guidelines

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs