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
$103.30
Apple Inc.
+0.80
MSFT
$45.09
Microsoft Corpora
-0.34
GOOG
$577.33
Google Inc.
+5.73

MacTech Search:
Community Search:

Software Updates via MacUpdate

TextSoap 7.4.0 - Flexible text editing u...
TextSoap is for people who work with text. TextSoap effortlessly cleans up text from endlessly different formats. Wash away unwanted characters, spaces, tabs. Fix paragraphs with hard returns at the... Read more
NetShade 6.0.2 - Browse privately using...
NetShade is an Internet security tool that conceals your IP address on the web. NetShade routes your Web connection through either a public anonymous proxy server, or one of NetShade's own dedicated... Read more
Mac DVDRipper Pro 5.0 - Copy, backup, an...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
pwSafe 3.1 - Secure password management...
pwSafe provides simple and secure password management across devices and computers. pwSafe uses iCloud to keep your password databases backed-up and synced between Macs and iOS devices. It is... Read more
StatsBar 1.8 - Monitor system processes...
StatsBar gives you a comprehensive and detailed analysis of the following areas of your Mac: CPU usage Memory usage Disk usage Network and bandwidth usage Battery power and health (MacBooks only)... Read more
Path Finder 6.5.5 - Powerful, award-winn...
Path Finder is a file browser that combines the familiar Finder interface with the powerful utilities and innovative features. Just a small selection of the Path Finder 6 feature set: Dual pane... Read more
QuarkXPress 10.2.1 - Desktop publishing...
With QuarkXPress, you can communicate in all the ways you need to -- and always look professional -- in print and digital media, all in a single tool. Features include: Easy to Use -- QuarkXPress is... Read more
Skype 6.19.0.450 - Voice-over-internet p...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
Capo 3.1.2 - Slow down and learn to play...
Capo lets you slow down your favorite songs so you can hear the notes and learn how they are played. With Capo, you can quickly tab out your songs atop a highly-detailed OpenCL-powered spectrogram... Read more
VueScan 9.4.41 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more

Latest Forum Discussions

See All

Modern Combat 5 Gets a Major Multiplayer...
Modern Combat 5 Gets a Major Multiplayer Update Posted by Jessica Fisher on September 2nd, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Alien Creeps TD Review
Alien Creeps TD Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: EXPENSIVE DEFENSESUniversal App - Designed for iPhone and iPad Alien Creeps TD would be a fun if unremarkable Tower Defense game, but its heavy focus on... | Read more »
The Journey Down: Chapter Two Review
The Journey Down: Chapter Two Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: DARK YET ENTICINGUniversal App - Designed for iPhone and iPad It’s a little dark, in every sense of the word, but The Journey Down:... | Read more »
Function Space, a Social Network App for...
Function Space, a Social Network App for Science, Launches on iOS Posted by Ellis Spice on September 2nd, 2014 [ permalink ] | Read more »
Stupidfast – How Taylor Martinez Switche...
How do you make an Endless Running game more than just another Endless Running game? By adding real life prizes to it, of course! That’s the thinking behind StupidFast: a game designed for football enthusiasts, and the brainchild of former college... | Read more »
Little Raiders: Robin’s Revenge Review
Little Raiders: Robin’s Revenge Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: CASUAL RAIDINGUniversal App - Designed for iPhone and iPad Combining simple combat with village building is a potent combination for... | Read more »
Treasure Tombs: Ra Deal Coming from Bulk...
Treasure Tombs: Ra Deal Coming from Bulkypix and Dark Tonic This Fall Posted by Jessica Fisher on September 2nd, 2014 [ permalink ] Dark Tonic and | Read more »
Pirate Bash Review
Pirate Bash Review By Nadia Oxford on September 2nd, 2014 Our Rating: :: BAD PIRATES, GOOD TIMESUniversal App - Designed for iPhone and iPad Pirate Bash’s turn-based battles add an intriguing twist to a typical physics game.   | Read more »
Tiny Tower Vegas Review
Tiny Tower Vegas Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: STEADY DEVELOPMENTUniversal App - Designed for iPhone and iPad Build a huge tower again but Vegas-style in Tiny Tower Vegas.   | Read more »
The Manhattan Project Review
The Manhattan Project Review By Andrew Fisher on September 2nd, 2014 Our Rating: :: ROCKET SCIENCEUniversal App - Designed for iPhone and iPad The Manhattan Project offers a great Euro-style gameplay experience, but it is totally... | Read more »

Price Scanner via MacPrices.net

Apple Cuts iPad mini Prices; Non-apple Vendor...
Digitimes’ Max Wang and Joseph Tsai report that Apple is cooperating with US-based retailers including Best Buy and Amazon to cut iPad mini prices, and that channel retailers believe other brand... Read more
Apple refurbished iPads available for up to $...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
Are We Now In The Post-Post-PC Era?
A longtime and thoroughgoing laptop aficionado, I was more than a little dismayed by Steve Jobs’s declaration back in 2010 when he sprang the iPad on an unsuspecting world. that we’d entered a “post-... Read more
PC Outlook Improves, But 2014 Shipments Still...
According to the International Data Corporation (IDC) Worldwide Quarterly PC Tracker, worldwide PC shipments are expected to fall by -3.7 percent in 2014. To hat’s actually an improvement from the... Read more
IDC Lowers Tablet Sales Projections for 2014...
Following a second consecutive quarter of softer than expected demand, International Data Corporation (IDC) has lowered its worldwide tablet plus 2-in-1 forecast for 2014 to 233.1 million units. The... Read more
Apple now offering refurbished 21-inch 1.4GHz...
The Apple Store is now offering Apple Certified Refurbished 21″ 1.4GHz iMacs for $929 including free shipping plus Apple’s standard one-year warranty. Their price is $170 off the cost of new models,... Read more
Save $50 on the 2.5GHz Mac mini, on sale for...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more
Save up to $300 on an iMac with Apple refurbi...
The Apple Store has Apple Certified Refurbished iMacs available for up to $300 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more
The Rise of Phablets
Carlisle & Gallagher Consulting Group, a businesses and technology consulting firm focused solely on the financial services industry, has released an infographic depicting the convergence of... Read more
Bad Driver Database App Allows Good Drivers t...
Bad Driver Database 1.4 by Facile Group is a new iOS and Android app that lets users instantly input and see how many times a careless, reckless or just plain stupid driver has been added to the... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.