Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: Getting started with Java 2D - JavaWorld - July 1998

Getting started with Java 2D - JavaWorld - July 1998

Tutorial Details:

Getting started with Java 2D
Getting started with Java 2D
By: By Bill Day
New support for 2D shapes, transforms, curves, and fonts enters the core environment with Java 1.2
he Java 2D API is a core Java 1.2 platform API (see Resources for a variety of information on the API and its implementations). Implementations of the API are available as a part of the Java Foundation Classes (JFC) in the current beta releases of the Sun JDK for Windows NT/95 and Solaris. As Java 1.2 is finalized, Java 2D should become available on more platforms.
Note that although Java 2D has been developed somewhat independently of the other parts of the JFC, it is nonetheless a core part of the 1.2 AWT. We will make the distinction and point out 2D-specific features for discussion, but you should remember that this functionality is just as central to 1.2 graphics as the old 1.0 and 1.1 AWT support.
Java 2D extends the previous AWT mechanisms for drawing 2D graphics, manipulating text and fonts, loading and using images, and defining and dealing with colors and color spaces. We will be exploring these new mechanisms in this and future columns.
A note about nomenclature and conventions
For this column, my primary development platform will be a PC running Windows 95 or Windows NT. I hope to provide other platform-specific tips and tricks where possible, but I will focus on Windows since that's where I will be spending most of my time.
When I write a method name, it should always be of the form methodname() . The trailing parentheses are meant to set this apart as a method. The method may or may not take parameters. In practice, the context should always make this clear.
Source code listings will be given with line numbers included. I plan to use the line numbers to cross-reference the article text and the code listings as appropriate. This should also make it much easier for you to annotate the column, should you chose to print a copy. Please note, however, that the source files linked from the column will be regular *.java files (sans line numbers) so that you can download and develop with them.
Because I will be writing about many of the Media and Communications APIs in the coming months, I want to make sure that all of the sample code makes sense as a whole as well as in its individual parts. I will attempt to consistently name my examples and place them into sensical packages.
The top of my package hierarchy will be:
com.javaworld.media
Each API or topic that I write about will have at least one subpackage under this top level. For instance, all of the code for this Java 2D article will be in:
com.javaworld.media.j2d
So, to invoke the first example application on Java 2D, you would download the code, put it in your classpath, then use:
java com.javaworld.media.j2d.Example01
(If the namespace is too long for your liking or for some other reason you want to use the example code without having to use the fully qualified name, simply comment out the package line at the beginning of each source code file.)
I will generate a Java Archive (jar) file for each article's example code and class files. This archive will be made available in the Resources of each column, should you wish to download it and execute the examples from within the archive.
I will also keep an up-to-date jar file containing all of the code and classes from my current and previous Media Programming columns. This all-encompassing jar file will be available on my personal Web site.
One final point on the examples: I have chosen to make each example, unless I specifically note otherwise, a standalone application or applet. This will lead to some repetition of code from time to time, but I feel it best preserves the integrity of each individual example.
Enough about conventions. Let's get started programming with Java 2D!
Graphics2D: A better Graphics class
The central class within the Java 2D API is the java.awt.Graphics2D abstract class, which subclasses java.awt.Graphics to extend 2D rendering functionality. Graphics2D adds more uniform support for manipulations of a variety of shapes, in effect making text, lines, and all sorts of other two-dimensional shapes comparable in their capabilities and utility.
Let's start with a simple example showing how you get and use a Graphics2d reference.
001 package com.javaworld.media.j2d;
002
003 import java.awt.*;
004 import java.awt.event.*;
005
006 public class Example01 extends Frame {
007 /**
008 * Instantiates an Example01 object.
009 **/
010 public static void main(String args[]) {
011 new Example01();
012 }
013
014 /**
015 * Our Example01 constructor sets the frame's size, adds the
016 * visual components, and then makes them visible to the user.
017 * It uses an adapter class to deal with the user closing
018 * the frame.
019 **/
020 public Example01() {
021 //Title our frame.
022 super("Java 2D Example01");
023
024 //Set the size for the frame.
025 setSize(400,300);
026
027 //We need to turn on the visibility of our frame
028 //by setting the Visible parameter to true.
029 setVisible(true);
030
031 //Now, we want to be sure we properly dispose of resources
032 //this frame is using when the window is closed. We use
033 //an anonymous inner class adapter for this.
034 addWindowListener(new WindowAdapter()
035 {public void windowClosing(WindowEvent e)
036 {dispose(); System.exit(0);}
037 }
038 );
039 }
040
041 /**
042 * The paint method provides the real magic. Here we
043 * cast the Graphics object to Graphics2D to illustrate
044 * that we may use the same old graphics capabilities with
045 * Graphics2D that we are used to using with Graphics.
046 **/
047 public void paint(Graphics g) {
048 //Here is how we used to draw a square with width
049 //of 200, height of 200, and starting at x=50, y=50.
050 g.setColor(Color.red);
051 g.drawRect(50,50,200,200);
052
053 //Let's set the Color to blue and then use the Graphics2D
054 //object to draw a rectangle, offset from the square.
055 //So far, we've not done anything using Graphics2D that
056 //we could not also do using Graphics. (We are actually
057 //using Graphics2D methods inherited from Graphics.)
058 Graphics2D g2d = (Graphics2D)g;
059 g2d.setColor(Color.blue);
060 g2d.drawRect(75,75,300,200);
061 }
062 }
When you execute Example01 , you should see a red square and blue rectangle, as shown in the figure below. Note that there is a known performance problem with the Windows NT/95 version of the JDK 1.2 Beta 3 (the most current 1.2 release as of this column). If this example is painfully slow on your system, you may need to work around the bug as documented in JavaWorld Java Tip 55 (see Resources below for this tip).
Simple graphics using Graphics and Graphics2D
Note that just as you do not directly instantiate a Graphics object, you do not instantiate a Graphics2D object either. Rather, the Java runtime constructs a rendering object and passes it to paint() (line 047 in the Example01 code listing), and on Java 1.2 platforms and beyond, this object implements the Graphics2D abstract class as well.
So far we haven't done anything particularly special with our 2D graphics capabilities. Let's add some code to the end of our previous example's paint() method and bring in several features new to Java 2D ( Example02 ):
001 /**
002 * Here we use new Java 2D API features such as affine
003 * transforms and Shape objects (in this case a generic
004 * one, GeneralPath).
005 **/
006 public void paint(Graphics g) {
007 g.setColor(Color.red);
008 g.drawRect(50,50,200,200);
009
010 Graphics2D g2d = (Graphics2D)g;
011 g2d.setColor(Color.blue);
012 g2d.drawRect(75,75,300,200);
013
014 //Now, let's draw another rectangle, but this time, let's
015 //use a GeneralPath to specify it segment by segment.
016 //Furthermore, we're going to translate and rotate this
017 //rectangle relative to the Device Space (and thus, to
018 //the first two quadrilaterals) using an AffineTransform.
019 //We also will change its color.
020 GeneralPath path = new GeneralPath(GeneralPath.EVEN_ODD);
021 path.moveTo(0.0f,0.0f);
022 path.lineTo(0.0f,125.0f);
023 path.lineTo(225.0f,125.0f);
024 path.lineTo(225.0f,0.0f);
025 path.closePath();
026
027 AffineTransform at = new AffineTransform();
028 at.setToRotation(-Math.PI/8.0);
029 g2d.transform(at);
030 at.setToTranslation(50.0f,200.0f);
031 g2d.transform(at);
032
033 g2d.setColor(Color.green);
034 g2d.fill(path);
035 }
Note that since GeneralPath is located in the java.awt.geom package, we need to be sure we add an import line as well:
import java.awt.geom.*;
The output of Example02 is shown in the following figure.
GeneralPath and AffineTransform illustrate drawing and transformations in Java 2D
Java 2D allows for the specification of arbitrary shapes using the java.awt.Shape interface. A variety of default shapes such as rectangles, polygons, 2D lines, etc., implement this interface. One of the most interesting of these in terms of flexibility is java.awt.geom.GeneralPath .
GeneralPath s let you describe a path with an arbitrary number of edges and a potentially extremely complex shape. In Example02, we have created a rectangle (lines 020-025), but we just as easily could have added another side or sides to make a pentagon, or heptagon, or some other multi-sided polygon. Also note that unlike standard Graphics code, Java 2D allows us to specify coordinates using floating-point numbers instead of integers. CAD vendors of the world, rejoice! In fact, Java 2D supports integer , double , and floating arithmetic in many places.
You probably also noticed that when we created the path we passed a parameter, GeneralPath.EVEN_ODD , into the constructor (line 020). This parameter represents a winding rule that tells the renderer how to determine the inside of the shape specified by our path. Please refer to the Java 2D javadoc documentation refere


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Getting started with Java 2D - JavaWorld - July 1998

View Tutorial:
Getting started with Java 2D - JavaWorld - July 1998

Related Tutorials:

J2SE 1.4 breathes new life into the CORBA community, Part 1
J2SE 1.4 breathes new life into the CORBA community, Part 1
 
The Java Web Services Tutorial
This tutorial is a beginner\'s guide to developing Web services and Web applications using the Java Web Services Developer Pack (Java WSDP).
 
Juggling JOGL
This article introduces the concepts in JOGL, the Java bindings to OpenGL, that are applicable to 2D gaming. We start with the handling of coordinate spaces and how they\'re scaled from the OpenGL world to the screen. Then we integrated JOGL\'s built-in A
 
Eye Of Newt - LDAP Editor
Eye Of Newt - LDAP Editor
 
Excerpt from Apache Axis Live
Excerpt from Apache Axis Live This chapter, "Getting Started with the Apache Axis Project," you will take "a brief look at what Axis is and how it implements some of the SOAP services.
 
Java 2D imaging for the Standard Widget Toolkit
Java 2D imaging for the Standard Widget Toolkit Bring the power of 2D imaging to your Eclipse plug-ins In this article, however, you'll learn how to have the best of both worlds. I'll demonstrate a simple technique that will allow you to paint Java
 
Software Download Central compatible.
GNU getopt - Java port A while back I found myself in need of a Java command line option parser. Unsatisfied with free versions I was able to find on the net, I volunteered to port the GNU getopt family of functions from C to Java. The current release
 
Getting Started with Java and Bluetooth
What is Bluetooth? What exactly is Bluetooth? Well, simply stated, Bluetooth is a wireless communication protocol. Since it\'s a communication protocol, you can use Bluetooth to communicate to other Bluetooth-enabled devices. In this sense, Bluetooth is
 
G (2D graphic library)
G is a generic graphics library built on top of Java 2D in order to make scene graph oriented 2D graphics available to client applications in a high level, easy to use way
 
Core Java Data Objects Excerpt
This book excerpt is from Core Java Data Objects,
 
Practically Groovy: Unit test your Java code faster with Groovy
Why unit test with Groovy? What makes Groovy particularly appealing with respect to other scripting platforms is its seamless integration with the Java platform. Because it's based on the Java language (unlike other alternate languages for the JRE, which
 
yawiki (Yet Another Wiki)
yawiki (Yet Another Wiki) A wiki system is a perfect place for working together and sharing informations. The syntax for the wiki system is really simple to learn. Getting started with a wiki system is easy.
 
Java Resources
There are all Java freebies. Some of these are old, and not under maintenance. Download and use them at your risk. In case of queries, mail subrahmanyam_avb@technologist.com or varalakshmi_a@techie.com.
 
The JavaTM Web Services Tutorial
A beginner's guide to developing Web services and Web applications on the Java Web Services Developer Pack
 
Getting Started with Java Message Service (JMS)
The Java Message Service (JMS) is designed to allow Java applications to use enterprise messaging systems. It makes it easy to develop enterprise applications that asynchronously send and receive business data and events. Learn how to implement it for you
 
Getting Started With the Mobile 3D Graphics API for J2ME
This tutorial introduces the Mobile 3D Graphics API for J2ME, JSR 184. The article presents an overview, potential application areas, the differences between JSR 184 and two related APIs, the classes in the new optional package, the programming model, the
 
Getting Started with SIP API for J2ME (JSR 180)
Getting Started with SIP API for J2ME (JSR 180) This article presents an overview of SIP, the Session Initiation Protocol (SIP) a signaling protocol used for establishing and controlling sessions on telecommunication networks based on the Internet Protoco
 
Getting Started With Bluetooth
JSR-82 brings Bluetooth API's to the J2ME environment. Read the tech tip and begin experimenting with Bluetooth today using the Wireless Toolkit 2.2 Beta.
 
Getting Started with Java Management Extensions (JMX): Developing Management and Monitoring Solutions
The Java Management Extensions (JMX) API is a standard specification developed through the Java Community Process (JCP) as JSR 3 for managing and monitoring applications and services.
 
Getting Started With the PIM APIs
This article provides a code-intensive introductory tutorial to Personal information management (PIM) APIs, JSR 75.
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.