TweetFollow Us on Twitter

Jan 97 Getting Started

Volume Number: 13 (1997)
Issue Number: 1
Column Tag: Getting Started

Java's AWT Shapes

By Dave Mark

Two of the first things any Mac programmer learns are the concept of event-loop programming and drawing using QuickDraw. The Java programming learning curve is quite similar in this respect. Last month, we introduced Java's event handling mechanism. This month, we'll explore the java.awt.Graphics class. Specifically, we'll look at the java.awt.Graphics member functions that allow you to draw shapes in your applet window.

The java.awt.Graphics Shapes

This month's applet is called javaDraw. Before you dig into the code, take some time to read the java.awt.Graphics web page (part of the JDK API Documentation from Sun.) Pay special attention to the function names that start with either the words draw or frame. The draw routines are analogous to the QuickDraw paint routines (like PaintRect()) and the frame routines do the same as the QuickDraw frame routines (like FrameRect()).

Creating the javaDraw Project

Create a new project called javaDraw.µ using the Java applet stationery. Create a new source code file named javaDraw.html and add it to the project (replace any existing html file that may have been added to the project.) Here's the html code:

<title>javaDraw</title>
<hr>
<applet codebase="javaDraw Classes" code="javaDraw.class" width=228 height=160>
</applet>
<hr>
<a href="javaDraw.java">The source.</a>

Next, create a second source code file named javaDraw.java and add it to the project as well (replace any default .java file that may have been added to the project.) Here's the Java code:

import java.awt.*;

public class shapeCanvas extends Canvas
{
 final int  rectangle=0,
 rect3D=1,
 roundRect=2,
 arc=3,
 oval=4,
 line=5,
 polygon=6;
 int    whichShape = rectangle;
 booleanisFilled = true;
 
 shapeCanvas( int width, int height )
 {
 setBackground( Color.yellow );
 setForeground( Color.red );
 resize( width, height );
 }
 
 public void SetShape( int newShape )
 {
 whichShape = newShape;
 }
 
 public void SetIsFilled( boolean newIsFilled )
 {
 isFilled = newIsFilled;
 }
 
 public void paint( Graphics g )
 {
 Rectangler, b;
 Polygonpoly;
 
 b = bounds();
 r = new Rectangle( 10, 10, b.width - 20,
 b.height - 20 );
 
 poly = new Polygon();
 poly.addPoint( r.x, r.y );
 poly.addPoint( r.x, r.y + r.height );
 poly.addPoint( r.x + r.width, r.y + r.height );
 poly.addPoint( r.x, r.y + r.height/2 );
 poly.addPoint( r.x + r.width, r.y + r.height/2 );
 poly.addPoint( r.x, r.y );
 
 if ( isFilled )
 {
 switch ( whichShape )
 {
 case rectangle:
 g.fillRect( r.x, r.y, r.width, r.height );
 break;
 case rect3D:
 g.fill3DRect( r.x, r.y, r.width, r.height, true );
 break;
 case roundRect:
 g.fillRoundRect( r.x, r.y, r.width, r.height,
 16, 16 );
 break;
 case arc:
 g.fillArc( r.x, r.y, r.width, r.height, 0, 270 );
 break;
 case oval:
 g.fillOval( r.x, r.y, r.width, r.height );
 break;
 case line:
 g.drawLine( r.x, r.y, r.x + r.width, r.y + r.height           
 );
 break;
 case polygon:
 g.fillPolygon( poly );
 break;
 }
 }
 else
 {
 switch ( whichShape )
 {
 case rectangle:
 g.drawRect( r.x, r.y, r.width, r.height );
 break;
 case rect3D:
 g.draw3DRect( r.x, r.y, r.width, r.height, true );
 break;
 case roundRect:
 g.drawRoundRect( r.x, r.y, r.width, r.height,
 16, 16 );
 break;
 case arc:
 g.drawArc( r.x, r.y, r.width, r.height, 0, 270 );
 break;
 case oval:
 g.drawOval( r.x, r.y, r.width, r.height );
 break;
 case line:
 g.drawLine( r.x, r.y, r.x + r.width,
 r.y + r.height );
 break;
 case polygon:
 g.drawPolygon( poly );
 break;
 }
 }
 }
}

public class javaDraw extends java.applet.Applet
{
 private Choice  shapePopup, fillPopup;
 private shapeCanvas sCanvas;
 
 public void init()
 {
 shapePopup = new Choice();
 shapePopup.addItem( "Rectangle" );
 shapePopup.addItem( "3D Rectangle" );
 shapePopup.addItem( "Rounded Rectangle" );
 shapePopup.addItem( "Arc" );
 shapePopup.addItem( "Oval" );
 shapePopup.addItem( "Line" );
 shapePopup.addItem( "Polygon" );
 
 add( shapePopup );
 
 fillPopup = new Choice();
 fillPopup.addItem( "Fill Shapes" );
 fillPopup.addItem( "Do Not Fill Shapes" );
 
 add( fillPopup );
 
 sCanvas = new shapeCanvas( 208, 110 );
 add( sCanvas );
 }
 public boolean action( Event e, Object obj )
 {
 if ( e.target == shapePopup )
 {
 sCanvas.SetShape( shapePopup.getSelectedIndex() );
 sCanvas.repaint();
 
 return true;
 }
 else if ( e.target == fillPopup )
 {
 sCanvas.SetIsFilled( fillPopup.getSelectedIndex()
 == 0 );
 sCanvas.repaint();
 
 return true;
 }
 else
 return super.action( e, obj );
 }
}

If you would like to specify the application used to run your applet, select Project Settings... from CodeWarrior's Edit menu, then click on the Project/Java Project item in the scrolling list (see Figure 1.) Click on the Set... button and select your preferred applet runner from the standard get file dialog. The screen shots that I used in this column were taken using the Metrowerks Java applet runner that comes with CodeWarrior.

Figure 1. CodeWarrior's Project Setting's dialog, showing the Java Project options.

No matter what applet runner you use, be sure you specify "javaDraw Classes" in the File Name field, to match the "codebase" parameter in your html file.

Once everything is entered and set up just the way you like it, select Run from the Project menu to compile and run your applet. Figure 2 shows the javaDraw applet as it first appears. The applet area consists of two popup menus (known as choices in java-speak) and a canvas area. The top popup lets you select the type of shape you are interested in seeing, and the bottom popup lets you specify whether the shape is drawn or framed (filled or outlined.) The default setting is a filled rectangle.

Figure 2. The javaDraw applet, as it first appears.

Figure 3 shows a framed arc. Take some time to play with all the awt.Graphics shapes, in both framed and filled modes. Note that lines look the same in either mode (both call the same function) and that 3D rectangles look almost exactly the same as rectangles. I'm not sure why this last is true, but hopefully future versions of awt will implement more interesting 3D rectangles.

Figure 3. The javaDraw applet, this time showing a framed arc.

Walking Through the Source

javaDraw consists of two classes. The shapeCanvas class implements the yellow drawing canvas at the bottom of the applet area. The javaDraw class extends the applet class and initiates a shapeCanvas and the two popup menus. We'll start with the shapeCanvas class.

shapeCanvas extends the Canvas class. It starts with a series of constants specified using the final keyword. If a variable is marked as final, it becomes a constant - its initial value may not be changed. The constants represent the items in the shape popup menu. Notice that the first constant was set to zero. That's because popup menu items are zero based.

import java.awt.*;

public class shapeCanvas extends Canvas
{
 final int  rectangle=0,
 rect3D=1,
 roundRect=2,
 arc=3,
 oval=4,
 line=5,
 polygon=6;
 int    whichShape = rectangle;
 booleanisFilled = true;

The shapeCanvas() constructor sets the Canvas background and foreground colors, then sets the Canvas size to the specified width and height. SetShape() is used to set the whichShape class variable to the current shape, as specified by the popup menu. SetIsFilled() does the same thing for the isFilled boolean, setting it depending on the bottom popup menu setting.

 shapeCanvas( int width, int height )
 {
 setBackground( Color.yellow );
 setForeground( Color.red );
 resize( width, height );
 }
 
 public void SetShape( int newShape )
 {
 whichShape = newShape;
 }
 
 public void SetIsFilled( boolean newIsFilled )
 {
 isFilled = newIsFilled;
 }

The paint() method is called when the Canvas needs to be redrawn. It starts by retrieving the bounding rectangle of the Canvas. This rectangle is inset 10 pixels on each side, with the results stored in r (r is inset inside b).

 public void paint( Graphics g )
 {
 Rectangler, b;
 Polygonpoly;
 
 b = bounds();
 r = new Rectangle( 10, 10, b.width - 20,
 b.height - 20 );

Next, we create a new Polygon and add a series of points to the Polygon, creating a zigzag shape and ending at the same point we started. This last step is important since it "closes" the Polygon. The Polygon is only needed if it is actually selected from the popup. So, we should probably embed this code in the polygon case below. Sorry about my laziness!

 poly = new Polygon();
 poly.addPoint( r.x, r.y );
 poly.addPoint( r.x, r.y + r.height );
 poly.addPoint( r.x + r.width, r.y + r.height );
 poly.addPoint( r.x, r.y + r.height/2 );
 poly.addPoint( r.x + r.width, r.y + r.height/2 );
 poly.addPoint( r.x, r.y );


The rest of paint() is made up of a giant if. The first part of the if paints filled shapes. The second part of the if paints framed shapes. Take a look at each of these functions, for they are the heart and soul of the Graphics class. These are the functions that actually draw the Java shapes.

 if ( isFilled )
 {
 switch ( whichShape )
 {
 case rectangle:
 g.fillRect( r.x, r.y, r.width, r.height );
 break;
 case rect3D:
 g.fill3DRect( r.x, r.y, r.width, r.height, true );
 break;
 case roundRect:
 g.fillRoundRect( r.x, r.y, r.width, r.height,
 16, 16 );
 break;
 case arc:
 g.fillArc( r.x, r.y, r.width, r.height, 0, 270 );
 break;
 case oval:
 g.fillOval( r.x, r.y, r.width, r.height );
 break;
 case line:
 g.drawLine( r.x, r.y, r.x + r.width,
 r.y + r.height );
 break;
 case polygon:
 g.fillPolygon( poly );
 break;
 }
 }
 else
 {
 switch ( whichShape )
 {
 case rectangle:
 g.drawRect( r.x, r.y, r.width, r.height );
 break;
 case rect3D:
 g.draw3DRect( r.x, r.y, r.width, r.height, true );
 break;
 case roundRect:
 g.drawRoundRect( r.x, r.y, r.width, r.height,
 16, 16 );
 break;
 case arc:
 g.drawArc( r.x, r.y, r.width, r.height, 0, 270 );
 break;
 case oval:
 g.drawOval( r.x, r.y, r.width, r.height );
 break;
 case line:
 g.drawLine( r.x, r.y, r.x + r.width,
 r.y + r.height );
 break;
 case polygon:
 g.drawPolygon( poly );
 break;
 }
 }
 }
}

The javaDraw class implements the applet itself. The init() method first creates the shape Choice, then the fill Choice, and finally the shapeCanvas.

public class javaDraw extends java.applet.Applet
{
 private Choice  shapePopup, fillPopup;
 private shapeCanvas sCanvas;
 public void init()
 {
 shapePopup = new Choice();
 shapePopup.addItem( "Rectangle" );
 shapePopup.addItem( "3D Rectangle" );
 shapePopup.addItem( "Rounded Rectangle" );
 shapePopup.addItem( "Arc" );
 shapePopup.addItem( "Oval" );
 shapePopup.addItem( "Line" );
 shapePopup.addItem( "Polygon" );
 
 add( shapePopup );
 
 fillPopup = new Choice();
 fillPopup.addItem( "Fill Shapes" );
 fillPopup.addItem( "Do Not Fill Shapes" );
 
 add( fillPopup );
 
 sCanvas = new shapeCanvas( 208, 110 );
 add( sCanvas );
 }

The applet's action() routine checks for events occurring in either popup. If the event was in the shape Choice, the shapeCanvas' SetShape() function is called, and an update event is queued for the canvas (repaint() is similar to invalRect(), though for an entire object. If the event was the fill Choice, the SetIsFilled() method is called and the canvas is again repainted. If neither case is true, the parent class' action() method is called and that result returned.

 public boolean action( Event e, Object obj )
 {
 if ( e.target == shapePopup )
 {
 sCanvas.SetShape( shapePopup.getSelectedIndex() );
 sCanvas.repaint();
 
 return true;
 }
 else if ( e.target == fillPopup )
 {
 sCanvas.SetIsFilled( fillPopup.getSelectedIndex()
 == 0 );
 sCanvas.repaint();
 
 return true;
 }
 else
 return super.action( e, obj );
 }
}

Till Next Month...

At this point, you should have a pretty good handle on Java's graphics mechanism. Spend some time exploring the rest of the Graphics class' methods. There are some pretty funky methods in there, and we'll get to them eventually. Before I sign off, I just wanted to mention that this column marks the start of my fifth year writing for MacTech Magazine. Can you believe it? Well, here's to four more years of Mac programming fun! See you next month...

 
AAPL
$100.89
Apple Inc.
-0.65
MSFT
$45.01
Microsoft Corpora
-0.17
GOOG
$577.86
Google Inc.
-2.34

MacTech Search:
Community Search:

Software Updates via MacUpdate

BBEdit 10.5.12 - Powerful text and HTML...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
Microsoft Office 2011 14.4.4 - Popular p...
Microsoft Office 2011 helps you create professional documents and presentations. And since Office for Mac 2011 is compatible with Office for Windows, you can work on documents with virtually anyone... Read more
TextWrangler 4.5.10 - Free general purpo...
TextWrangler is the powerful general purpose text editor, and Unix and server administrator's tool. Oh, and also, like the best things in life, it's free. TextWrangler is the "little brother" to... Read more
BitTorrent Sync 1.4.72 - Sync files secu...
BitTorrent Sync allows you to sync unlimited files between your own devices, or share a folder with friends and family to automatically sync anything. File transfers are encrypted. Your information... Read more
Cyberduck 4.5.2 - FTP and SFTP browser....
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Tinderbox 6.0.3 - Store and organize you...
Tinderbox is a personal content management assistant. It stores your notes, ideas, and plans. It can help you organize and understand them. And Tinderbox helps you share ideas through Web journals... Read more
Adobe Photoshop CC 2014 15.1.0 - Profess...
Photoshop CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Photoshop customer). Photoshop CS6 is still available for purchase (... Read more
Adobe InDesign CC 2014 10.0.0.70 - Profe...
InDesign CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous InDesign customer). InDesign CS6 is still available for purchase (... Read more
Adobe InCopy CC 2014 10.0.0.70 - Create...
InCopy CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous InCopy customer). InCopy CS6 is still available for purchase (without a... Read more
Adobe Illustrator CC 2014 18.0 - Profess...
Illustrator CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Illustrator customer). Illustrator CS6 is still available for... Read more

Latest Forum Discussions

See All

Appointment With F.E.A.R. (Games)
Appointment With F.E.A.R. 1.02 Device: iOS Universal Category: Games Price: $2.99, Version: 1.02 (iTunes) Description: Travel back to the 1980s as a superpowered defender of justice in this all-new edition of Steve Jackson's... | Read more »
8bit Doves (Games)
8bit Doves 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: “I dove it” – Pocket Gamer “They told me I could be whatever I want, so I became a flying hobo” – Cactus Wolf “Let’s you crash into... | Read more »
Madden NFL Mobile Review
Madden NFL Mobile Review By Blake Grundman on August 26th, 2014 Our Rating: :: FINALLY GETS IT RIGHTUniversal App - Designed for iPhone and iPad It looks like EA Sports has finally discovered how to tread the line between free-to-... | Read more »
Superhero Workout Review
Superhero Workout Review By Jennifer Allen on August 26th, 2014 Our Rating: :: SUPERCHARGEDUniversal App - Designed for iPhone and iPad Want a workout with a kind of story tied into it? Superhero Workout is what you’re after.   | Read more »
Star Wars: Commander Review
Star Wars: Commander Review By Jennifer Allen on August 26th, 2014 Our Rating: :: CLASH OF THE FORCEUniversal App - Designed for iPhone and iPad It’s a lot like Clash of Clans, but the use of the Star Wars license means you don’t... | Read more »
Ridge Racer Slipstream Update Adds New C...
Ridge Racer Slipstream Update Adds New Cars, Challenges, and Tracks Posted by Ellis Spice on August 26th, 2014 [ permalink ] | Read more »
Infinity Blade III: Kingdom Come, the Fi...
Infinity Blade III: Kingdom Come, the Final Update, Set to Arrive September Posted by Ellis Spice on August 26th, 2014 [ permalink ] | Read more »
Furious Climber Review
Furious Climber Review By Jordan Minor on August 26th, 2014 Our Rating: :: REACH FOR THE STARSUniversal App - Designed for iPhone and iPad Furious Climber’s rough packaging can’t ruin its awesomely awkward gameplay   | Read more »
Don’t Forget the Milk – Let Heap, the Gr...
Don’t Forget the Milk – Let Heap, the Grocery List App, Help You Stay Organized While Shopping Posted by Jessica Fisher on August 26th, 2014 [ permalink ] | Read more »
MZR Review
MZR Review By Rob Thomas on August 26th, 2014 Our Rating: :: MAZED AND CONFUSEDUniversal App - Designed for iPhone and iPad How quickly can you escape from MZR’s neon mazes of doom? Why not find out for yourself?   | Read more »

Price Scanner via MacPrices.net

Life Inventory iOS Apps – Learn to Know Thyse...
James Hollender’s Life Inventory apps s are now on sale with 20% off thru Labor Day, 09/01/2014. This is a great opportunity to get started on that Moral Inventory you’ve been putting off doing for... Read more
Pocket Watch, LLC. Reveals Cloud Server For P...
Beaumont, Texas based Pocket Watch, LLC. has announced the availability of its new ActivePrint Cloud Server Powered by Raspberry Pi. With this small standalone box almost any USB printer or available... Read more
902it Simplifies Area Code Changes For Nova S...
The east coast Canadian provinces of Nova Scotia and Prince Edward Island are phasing in 10 digit telephone dialing, to be fully in place by November, in order to accommodate a second area code to... Read more
Boomerang iPad Stand Mounts Your iPad Anywher...
Boomerang, a Mountable Stand with Multiple Viewing Angles, is now available for iPad Air. Boomerang combines several functions that aim to expand your iPad’s potential in one, elegant product. The... Read more
Retina MacBook Pros available starting at $10...
The Apple Store has Apple Certified Refurbished 13″ and 15″ MacBook Pros available starting at $929. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz MacBook Pros (4GB RAM/... Read more
Apple 27-inch Thunderbolt Display (refurbishe...
The Apple Store has Apple Certified Refurbished 27″ Thunderbolt Displays available for $799 including free shipping. That’s $200 off the cost of new models. Read more
Apple offers free $25 iTunes gift card with p...
The Apple Store is offering a free $25 iTunes Gift Card with the purchase of a $99 Apple TV for a limited time. Shipping is free. Read more
Apple’s 2014 Back to School promotion: $100 g...
 Apple’s 2014 Back to School promotion includes a free $100 App Store Gift Card with the purchase of any new Mac (Mac mini excluded), or a $50 Gift Card with the purchase of an iPad or iPhone,... Read more
iPhone Camera vs. Top Tier DSLR In Picture Qu...
If you’ve wondered just how good the iPhone 5s’s 8 megapixel rear-facing camera is in terms of image quality, The Verge has posted an excellent feature that should remove any ambiguity on the matter... Read more
Apple Announces Limited iPhone 5 Defective Ba...
Apple says it has determined that a very small percentage of iPhone 5 devices may suddenly experience shorter battery life or need to be charged more frequently. The affected iPhone 5 units were sold... Read more

Jobs Board

Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** Being a Business Manager at an Apple Store means you're the catalyst for businesses to discover and leverage the power, ease, and flexibility of Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.