The ACM Java Libraries
Andrew Mertz William Slough Nancy Van Cleave
Mathematics and Computer Science Department Eastern Illinois University
Introduction
NetBeans and Java
The ACM Java Task Force (JTF) Libraries
Placing applets on web pages
How to learn about the ACM libraries: This workshop
Textbooks
ACM library galleries
EIU student work:
http://www.eiu.edu/~mathcs/http
JTF demo gallery:
Installing the necessary software:
NetBeans
www.netbeans.org/downloads/
Click on theDownload NetBeans IDE Button
Installating the necessary software: ACM Java libraries
jtf.acm.org— obtainacm.zip Create acmLibraryproject in NetBeans
File →New Project
Within theCategoriespanel, selectJava
Within theProjects, selectJava Class Library
ClickNextto proceed
For the project name, enteracmLibrary
Click on theFinishbutton
Move the acm.zip file to theacmLibrary/srcdirectory
Unpack the zip file (into the acmLibrary/src directory)
The
Program
class diagram
JApplet
Program
A “Hello, world!” program
Create HelloProgram project File →New Project
Within theCategoriespanel, selectJava
Within theProjects, selectJava Class Library
ClickNextto proceed
For the project name, enterHelloProgram
Click on theFinishbutton
Make the acmLibraryavailable to this project Right–click onLibraries, selectAdd Project
In theAdd Projectwindow chooseacmLibrary
Create a new Java program
Right–click onSource Packages, then select New→ Other
SelectJava from the categories
The file type to select is Empty Java File
ClickNext, then replace the suggested class name NewEmpty
with HelloProgram
A “Hello, world!” program: in a console window
import acm.graphics.*; import acm.program.*;
public class HelloProgram extends ConsoleProgram { public void run() {
println("Hello, world!"); }
}
Modifications:
A “Hello, world!” program: with dialog boxes
import acm.graphics.*; import acm.program.*;
public class HelloProgram extends DialogProgram { public void run() {
println("Hello, world!"); println("Name here");
println("Organization here"); }
}
Modifications:
ChangeConsoleProgram to DialogProgram
A “Hello, world!” program: in a graphics window
import acm.graphics.*; import acm.program.*;
public class HelloProgram extends GraphicsProgram { public void run() {
add(new GLabel("Hello, world!", 100, 75)); }
}
Modifications:
Move the output line down
Placing applets on a web site
index.html
Add2Quantities
import acm.program.*;
public class Add2Quantities extends ConsoleProgram { public void run() {
println("This program adds two values:"); int a = readInt("Enter a: ");
int b = readInt("Enter b: "); int sum = a + b;
println("The sum is " + sum + "."); }
}
Modifications:
Convert to a DialogProgram
Different data types:
The
acm.graphics
model
Theacm.graphicspackage uses acollage model in which you create an image by adding various objects to a canvas.
This is similar to a felt board that serves as a backdrop for colored shapes that stick to the felt surface.
The Java coordinate system
All distances and coordinates in the graphics library are measured inpixels.
Coordinates in the graphics model are specified relative to the originin the upper left corner of the screen.
Partial class diagram for
acm.graphics
java.awt.Container
GCanvas GObject GCompound
GLabel GRect
GOval
GLine
GPolygon
GImage
GArc
The
GCanvas
class
TheGCanvasclass represents the background canvas, a virtual felt board.
When you use theacm.graphics package, you create pictures by adding variousGObjectsto a GCanvas.
For simple applications, you will not need to work with an explicit
GCanvasobject.
Programs that extendGraphicsProgram, automatically creates a
GCanvasand resizes it so that it fills the program window.
Methods in the GCanvas class
add(object) Adds the object to the canvas at the front of the stack
add(object, x, y) Moves the object to (x, y) and then adds it to the canvas
remove(object) Removes the object from the canvas
removeAll() Removes all objects from the canvas
getElementAt(x, y) Returns the front most object at (x, y), or null if none
getWidth() Returns the width in pixels of the canvas
getHeight() Returns the height in pixels of the canvas
Methods in the
GCanvas
class
The following methods are available in GraphicsProgram only: pause(milliseconds) Pauses the program for the specified time
Two forms of the
add
method
The add method comes in two forms. add(object);
adds the object at the location currently stored in its internal structure. You use this form when you have already set the coordinates of the object, usually done when it was created. The second form:
add(object, x, y);
Centering text
import acm.graphics.*; import acm.program.*;
public class CenteredLabel extends GraphicsProgram {
public void run() {
GLabel label = new GLabel("I am centered"); add(label,
(getWidth() - label.getWidth()) / 2, (getHeight() - label.getHeight()) / 2); }
Methods common to
GObject
s
setLocation(x, y) Resets the location of the object to the specified point
move(dx, dy) Moves the objectdxanddypixels
movePolar(r, theta) Moves the objectrpixels in the directiontheta
getX() Returns thexcoordinate of the object
getY() Returns theycoordinate of the object
getWidth() Returns the horizontal width of the object in pixels
getHeight() Returns the vertical height of the object in pixels
Methods common to
GObject
s (continued)
setColor(c) Sets the color of the object
getColor() Returns the color currently assigned to the object
setVisible(flag) Sets visibility (false= invisible,true= visible)
isVisible() Returnstrueif the object is visible
sendToFront() Sends the object to the front of the stacking order
sendToBack() Sends the object to the back of the stacking order
sendForward() Sends the object forward one position in the stack-ing order
Sharing behavior through interfaces
There are some methods that apply to someGObject subclasses, but not others.
For example, you can callsetFilled onGOvals orGRects. However, it does not make sense to callsetFilledon a GLine.
In theacm.graphics package, there are three interfaces that define methods for certainGObject subclasses:
acm.graphics
interfaces
GFillable(GArc,GOval,GPolygon,GRect)
setFilled(flag) Sets the fill state (false= outlined,true= filled)
isFilled() Returns the fill state
setFillColor(c) Sets the color used to fill the interior
getFillColor() Returns the fill color
GResizable(GImage,GOval,GRect)
setSize(width, height) Sets the dimensions of the object
setBounds(x, y, width, height) Sets the location and dimensions
GScalable(GArc,GCompound,GLine,GImage,GOval,GPolygon,GRect) scale(sf) Scales both dimensions of the object bysf
Encapsulated coordinates
Theacm.graphicspackage defines three classes:
GPoint GDimension GRectangle
These combine geometric information about coordinates and sizes into a single object.
GPoint encapsulates the x andy coordinates of a point
GDimension encapsulates width and height values that specify an object’s size
Gathering input
Event driven model
Most of the time the program is waiting for something (anevent) to occur
When an event occurs, the program responds appropriately
event Respond to
an event
Event occurs Response
complete
The Java event model
In Java, you indicate what events you wish to respond to by designating some object as alistenerfor that event.
Events the ACM library facilitates
Keyboard events: key presses and key releases. Identifies the key and whether shift, control and/or alt are also pressed.
Mouse events: motion, button presses and button releases. Motion events tell where the position of the mouse is now, how far it moved and if any buttons are pressed.
A simple event-driven program
import acm.graphics.*; import acm.program.*; import java.awt.event.*;
public class Dots extends GraphicsProgram { public void init() {
addMouseListeners(); }
public void mouseClicked(MouseEvent e) { GOval dot = new GOval(DOT_SIZE, DOT_SIZE); dot.setFilled(true);
add(dot,
e.getX() - DOT_SIZE/2, e.getY() - DOT_SIZE/2); }
How it works
TheaddMouseListenersmethod of acm.program.Program
enables mouse-event reporting.
Clicking the mouse generates aMouseEvent.
That event triggers a call to themouseClicked method.
The program responds by adding a newGOvalto the canvas.
acm.util.RandomGenerator
TheRandomGeneratorclass can generate pseudorandom integers, doubles, booleans, and colors.
Methods provided include:
nextBoolean(double p) Returns a random boolean value with the specified probability
nextColor() Returns a random opaque Color
nextDouble(double low, double high) Returns a random real number in the specified range
The
GMath
class
TheGMathclass has the following static methods:
sinDegrees(theta) Returns the sine oftheta, measured in degrees
cosDegrees(theta) Returns the cosine oftheta
tanDegrees(theta) Returns the tangent oftheta
toRadians(degrees) Converts an angle from degrees to radians
toDegrees(radians) Converts an angle from radians to degrees
distance(x, y) Returns the distance from the origin to(x, y)
distance(x0, y0, x1, y1) Returns the distance from(x0, y0)to(x1, y1)
round(x) Returns the closest int tox
angle(x, y) Returns the angle in degrees formed by the line connecting the origin to the point(x, y)
Adding a touch of color
public class Dots extends GraphicsProgram { public void init() {
addMouseListeners(); }
public void mouseClicked(MouseEvent e) { GOval dot = new GOval(DOT_SIZE, DOT_SIZE); dot.setFilled(true);
dot.setColor(rand.nextColor()); add(dot,
e.getX() - DOT_SIZE/2, e.getY() - DOT_SIZE/2); }
private static final double DOT_SIZE = 20; private static RandomGenerator rand =
Responding to mouse events
1. Define an init method that callsaddMouseListeners. 2. Write new definitions of any listener methods you need. The most common mouse events and associated listener methods:
Method When invoked
mouseClicked(e) when the user clicks the mouse
mousePressed(e) when the mouse button is pressed
mouseReleased(e) when the mouse button is released
mouseMoved(e) when the user moves the mouse
mouseDragged(e) when the mouse is dragged with the button down
Lines
public class Lines extends GraphicsProgram { private GPoint lastPoint;
public void init() {
lastPoint = new GPoint(getWidth()/2,getHeight()/2); addMouseListeners();
}
public void mouseClicked(MouseEvent e){
add(new GLine(lastPoint.getX(), lastPoint.getY(), e.getX(), e.getY()));
lastPoint.setLocation(e.getX(), e.getY()); }
DragLines
public class DragLines extends GraphicsProgram { public void init() {
addMouseListeners(); }
public void mousePressed(MouseEvent e) { line = new GLine(e.getX(), e.getY(),
e.getX(), e.getY()); add(line);
}
public void mouseDragged(MouseEvent e) { line.setEndPoint(e.getX(), e.getY()); }
Exercise: Dragging dots
DragObjects
public class DragObjects extends GraphicsProgram { public void init() {
GRect rect = new GRect(100, 100, 150, 100); rect.setFilled(true);
rect.setColor(Color.RED); add(rect);
GOval oval = new GOval(300, 115, 100, 70); oval.setFilled(true);
oval.setColor(Color.GREEN); add(oval);
addMouseListeners(); }
DragObjects
public void mouseDragged(MouseEvent e) { if(gobj != null){
gobj.move(e.getX() - last.getX(), e.getY() - last.getY()); last = new GPoint(e.getPoint()); }
}
public void mouseClicked(MouseEvent e) { if (gobj != null) gobj.sendToFront(); }
Mouse listeners
The ACM Java Libraries simplifies the JFC approach to mouse listeners.
To maximize efficiency, Java defines two distinct listener interfaces.
TheMouseListenerinterface responds to mouse events that happen relatively infrequently, such as clicking the mouse button.
GImage
The ACM Library makes displaying images very easy and you can still use all of the other features of Swing.
import acm.graphics.*; import acm.program.*; import javax.swing.*;
public class ShowPicture extends GraphicsProgram {
public void run() {
JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null);
String filename = chooser.getSelectedFile().getPath(); GImage image = new GImage(filename);
setSize((int) image.getWidth(), (int) image.getHeight()); add(image);
Animation
Thepausemethod allows for simple animations.
double windowWidth = getWidth(); double windowHeight = getHeight();
// calculate ball size and steps double size = 0.06 * windowWidth; double dx = size / 8.0;
double dy = size / 8.0;
Animation
GOval ball = new GOval(windowWidth/2.0,
windowHeight/2.0, size, size); ball.setColor(Color.RED);
ball.setFilled(true); ball.setFillColor(Color.ORANGE); add(ball);
int count = 0;
while (count < BOUNCES) {
if ((ball.getX() + size > windowWidth) || (ball.getX() <= 0.0)) {
dx = -dx; count++; }
if ((ball.getY() + size > windowHeight) || (ball.getY() <= 0.0)) {
dy = -dy; count++; }
Animation
GPolygon
TheGPolygonclass can be used to represent closed polygonal shapes.
Initially, aGPolygon has no vertices. Vertices are added via the following methods:
addArc(arcWidth, arcHeight, start, sweep)
Adds a series of edges to simulate an arc
addEdge(dx, dy) Adds an edge using the given dis-placement from the last vertex
addPolarEdge(r, theta) Adds an edge using the given polar coordinates
addVertex(x, y) Adds a vertex relative to the polygon origin
The coordinates of vertices are expressed with respect to the origin of the polygon (its location on a canvas).
Drawing a diamond
public class Diamond extends GraphicsProgram {
public void run() {
GPolygon diamond = new GPolygon(); diamond.addVertex(-30, 0);
diamond.addVertex(0, 40); diamond.addVertex(30, 0); diamond.addVertex(0, -40); diamond.setFilled(true);
diamond.setFillColor(Color.BLUE);
add(diamond, getWidth()/2, getHeight()/2); }
Exercise: Diamonds
GCompound
GCompoundobjects are like canvases, you can add otherGObjects to them.
Some ofGCompound’s methods:
add(gobj) Adds an object to thisGCompound
add(gobj, x, y) Adds an object at the point (x, y)
markAsComplete() Makes it illegal to add or remove elements
remove(gobj) Removes an object
removeAll() Removes all objects
The coordinates of vertices are expressed with respect to the origin of the compound object (its location on a canvas).
Turtles
TheGTurtleclass enables graphics using a LOGO-like model of a turtle moving across the screen leaving a trail.
forward(distance) Moves the turtle forward
hideTurtle() Hides the turtle
left(angle) Turns the specified number of degrees to the left
penDown() Lowers the pen
penUp() Raises the pen
right(angle) Turns the specified number of degrees to the left
setDirection(dir) Sets the direction in which the turtle is moving
setLocation(x, y) Moves to the point (x, y) without drawing a line
setSpeed(speed) Sets the speed of the turtle, 0 (slowest) and 1 (fastest)
Fractals
GTurtlecan be very useful for many types of graphics, especially fractals.
Snowflakes
public class Koch_1 extends GraphicsProgram {
private GTurtle turtle = new GTurtle(); private int order = 4;
private double length = 300;
public void init() { setSize(600, 600);
add(turtle, (getWidth() - length) / 2, (getHeight() - length) / 2); turtle.setSpeed(0.8);
turtle.penDown(); }
Snowflakes
private void zig(int order, double length) { if (order == 0) turtle.forward(length); else {
zig(order - 1, length / 3.0); turtle.left(60);
zig(order - 1, length / 3.0); turtle.right(120);
zig(order - 1, length / 3.0); turtle.left(60);
zig(order - 1, length / 3.0); }
}
Snowflakes
public void run() { zig(order, length); turtle.right(120); zig(order, length); turtle.right(120); zig(order, length); turtle.right(120); }
Exercise: Fractal
Make another fractal where the order 0 case is a square and the orderncase replaces each line of the order n−1 case with the following: