The ACM Java Libraries

bravesnailsΛογισμικό & κατασκευή λογ/κού

7 Ιουν 2012 (πριν από 5 χρόνια και 3 μήνες)

743 εμφανίσεις

The ACM Java Libraries
Andrew Mertz
William Slough
Nancy Van Cleave
Mathematics and Computer Science Department
Eastern Illinois University
October 10,2009
CCSC:MW 2009,Saint Xavier 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 Java Task Force Tutorial
Javadoc documentation
CCSC:MW 2009,Saint Xavier University
Textbook support for ACM libraries
CCSC:MW 2009,Saint Xavier University
ACM library galleries
EIU student work:
http://www.eiu.edu/
~
mathcs/http
JTF demo gallery:
http://jtf.acm.org/demos/index.html
CCSC:MW 2009,Saint Xavier University
Installing the necessary software:NetBeans
www.netbeans.org/downloads/
Click on the Download NetBeans IDE Button
Run install
CCSC:MW 2009,Saint Xavier University
Installating the necessary software:ACM Java libraries
jtf.acm.org | obtain acm.zip
Create acmLibrary project in NetBeans
File!New Project
Within the Categories panel,select Java
Within the Projects,select Java Class Library
Click Next to proceed
For the project name,enter acmLibrary
Click on the Finish button
Move the acm.zip le to the acmLibrary/src directory
Unpack the zip le (into the acmLibrary/src directory)
Right{click on the acmLibrary project in NetBeans,and
select close (don't shut down NetBeans)
CCSC:MW 2009,Saint Xavier University
The Program class diagram
JApplet
Program
GraphicsProgram
ConsoleProgram
DialogProgram
CCSC:MW 2009,Saint Xavier University
A\Hello,world!"program
Create HelloProgram project
File!New Project
Within the Categories panel,select Java
Within the Projects,select Java Class Library
Click Next to proceed
For the project name,enter HelloProgram
Click on the Finish button
Make the acmLibrary available to this project
Right{click on Libraries,select Add Project
In the Add Project window choose acmLibrary
Click on Add Project/Jar les
CCSC:MW 2009,Saint Xavier University
Create a new Java program
Right{click on Source Packages,then select New!Other
Select Java from the categories
The le type to select is Empty Java File
Click Next,then replace the suggested class name NewEmpty
with HelloProgram
Click the Finish button
CCSC:MW 2009,Saint Xavier University
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!");
}
}
Modications:
Add a second line below the rst with your name
Add a third line with your organization
CCSC:MW 2009,Saint Xavier University
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");
}
}
Modications:
Change ConsoleProgram to DialogProgram
Change rst two println statements to print statements
with\n to produce a single dialog window
CCSC:MW 2009,Saint Xavier University
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));
}
}
Modications:
Move the output line down
Add lines for your name and organization
CCSC:MW 2009,Saint Xavier University
Placing applets on a web site
index.html
HelloProgram.html
CCSC:MW 2009,Saint Xavier University
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 +".");
}
}
Modications:
Convert to a DialogProgram
Dierent data types:
int!double,readInt!readDouble
int!String,readInt!readLine
CCSC:MW 2009,Saint Xavier University
The acm.graphics model
The acm.graphics package uses a collage 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.
Note that newer objects can obscure those added earlier.This
layering arrangement is called the stacking order or z-order.
CCSC:MW 2009,Saint Xavier University
The Java coordinate system
All distances and coordinates in the graphics library are measured
in pixels.
Coordinates in the graphics model are specied relative to the
origin in the upper left corner of the screen.
Coordinate values are specied as a pair of oating-point values
(x;y) where the values for x increase as you move rightward across
the screen and the values for y increase as you move downward.
CCSC:MW 2009,Saint Xavier University
Partial class diagram for acm.graphics
java.awt.Container
GCanvas
GObject
GCompound
GLabel
GRect
GOval
GLine
GPolygon
GImage
GArc
GTurtle
CCSC:MW 2009,Saint Xavier University
The GCanvas class
The GCanvas class represents the background canvas,a virtual felt
board.
When you use the acm.graphics package,you create pictures by
adding various GObjects to a GCanvas.
For simple applications,you will not need to work with an explicit
GCanvas object.
Programs that extend GraphicsProgram,automatically creates a
GCanvas and resizes it so that it lls the program window.
Most of the methods dened for the GCanvas class are also
available in a GraphicsProgram,thanks to delegation.
CCSC:MW 2009,Saint Xavier University
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
setBackground(c)
Sets the background color of the canvas
CCSC:MW 2009,Saint Xavier University
Methods in the GCanvas class
The following methods are available in GraphicsProgram only:
pause(milliseconds)
Pauses the program for the specied time
waitForClick()
Suspends the program until the user clicks
the mouse
CCSC:MW 2009,Saint Xavier University
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);
which moves the object to the point (x;y) and then adds it there.
This form is useful when you need to determine some property of
the object before you know where to put it.If,for example,you
want to center a GLabel,you must rst create it and then use its
size to determine its location.
CCSC:MW 2009,Saint Xavier University
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);
}
}
CCSC:MW 2009,Saint Xavier University
Methods common to GObjects
setLocation(x,y)
Resets the location of the object to the specied
point
move(dx,dy)
Moves the object dx and dy pixels
movePolar(r,theta)
Moves the object r pixels in the direction theta
getX()
Returns the x coordinate of the object
getY()
Returns the y coordinate of the object
getWidth()
Returns the horizontal width of the object in pixels
getHeight()
Returns the vertical height of the object in pixels
contains(x,y)
Returns true if the object contains the specied
point
CCSC:MW 2009,Saint Xavier University
Methods common to GObjects (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()
Returns true if 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
sendBackward()
Sends the object backward one position in the stack-
ing order
CCSC:MW 2009,Saint Xavier University
Sharing behavior through interfaces
There are some methods that apply to some GObject subclasses,
but not others.
For example,you can call setFilled on GOvals or GRects.
However,it does not make sense to call setFilled on a GLine.
In the acm.graphics package,there are three interfaces that
dene methods for certain GObject subclasses:
GFillable
GResizable
GScalable
CCSC:MW 2009,Saint Xavier University
acm.graphics interfaces
GFillable (GArc,GOval,GPolygon,GRect)
setFilled(flag)
Sets the ll state (false = outlined,true = lled)
isFilled()
Returns the ll state
setFillColor(c)
Sets the color used to ll the interior
getFillColor()
Returns the ll 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 by sf
scale(sx,sy)
Scales the object by sx horizontally and sy vertically
CCSC:MW 2009,Saint Xavier University
Making a face
CCSC:MW 2009,Saint Xavier University
Exercise:Drawing a house
CCSC:MW 2009,Saint Xavier University
Encapsulated coordinates
The acm.graphics package denes three classes:
GPoint
GDimension
GRectangle
These combine geometric information about coordinates and sizes
into a single object.
GPoint encapsulates the x and y coordinates of a point
GDimension encapsulates width and height values that specify
an object's size
GRectangle encapsulates all four of these values by specifying
both the origin and size of a rectangle
CCSC:MW 2009,Saint Xavier University
Gathering input
Event driven model
Most of the time the program is waiting for something
(an event) to occur
When an event occurs,the program responds appropriately
event
Respond to
an event
Event occurs
Responsecomplete
Wait for
CCSC:MW 2009,Saint Xavier University
The Java event model
In Java,you indicate what events you wish to respond to by
designating some object as a listener for that event.
When the event occurs,a message is sent to the listener,which
triggers the appropriate response.
CCSC:MW 2009,Saint Xavier University
Events the ACM library facilitates
Keyboard events:key presses and key releases.Identies 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.
Action events:GUI buttons pressed and other user-interface
actions.
CCSC:MW 2009,Saint Xavier University
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);
}
private static final double DOT_SIZE = 20;
}
CCSC:MW 2009,Saint Xavier University
How it works
The addMouseListeners method of acm.program.Program
enables mouse-event reporting.
Clicking the mouse generates a MouseEvent.
That event triggers a call to the mouseClicked method.
The program responds by adding a new GOval to the canvas.
Subsequent mouse clicks are treated in exactly the same way.
CCSC:MW 2009,Saint Xavier University
acm.util.RandomGenerator
The RandomGenerator class can generate pseudorandom integers,
doubles,booleans,and colors.
Methods provided include:
nextBoolean(double p)
Returns a randomboolean value
with the specied probability
nextColor()
Returns a random opaque Color
nextDouble(double low,double high)
Returns a random real number
in the specied range
nextInt(int low,int high)
Returns a random integer in the
specied range
CCSC:MW 2009,Saint Xavier University
The GMath class
The GMath class has the following static methods:
sinDegrees(theta)
Returns the sine of theta,measured in degrees
cosDegrees(theta)
Returns the cosine of theta
tanDegrees(theta)
Returns the tangent of theta
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 to x
angle(x,y)
Returns the angle in degrees formed by the line
connecting the origin to the point (x;y)
angle(x0,y0,x1,y1)
Returns the angle in degrees formed by the line
connecting the points (x0;y0) and (x1;y1)
CCSC:MW 2009,Saint Xavier University
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 =
new RandomGenerator();
}
CCSC:MW 2009,Saint Xavier University
Responding to mouse events
1.Dene an init method that calls addMouseListeners.
2.Write new denitions 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
The parameter e is a MouseEvent object,which provides more
data about the event,such as the location of the mouse.
CCSC:MW 2009,Saint Xavier University
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());
}
}
CCSC:MW 2009,Saint Xavier University
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());
}
private GLine line;
}
CCSC:MW 2009,Saint Xavier University
Exercise:Dragging dots
Write a program that displays randomly colored dots whose size is
based on the amount the mouse is dragged.
CCSC:MW 2009,Saint Xavier University
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();
}
public void mousePressed(MouseEvent e) {
last = new GPoint(e.getPoint());
gobj = getElementAt(last);
}
...continues on next slide
CCSC:MW 2009,Saint Xavier University
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();
}
private GObject gobj;/* The object being dragged */
private GPoint last;/* The last mouse position */
}
CCSC:MW 2009,Saint Xavier University
Mouse listeners
The ACM Java Libraries simplies the JFC approach to mouse
listeners.
To maximize eciency,Java denes two distinct listener interfaces.
The MouseListener interface responds to mouse events that
happen relatively infrequently,such as clicking the mouse button.
The MouseMotionListener interface responds to the much more
rapid-re events that occur when you move or drag the mouse.
CCSC:MW 2009,Saint Xavier University
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);
}
}
CCSC:MW 2009,Saint Xavier University
Animation
The pause method 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;
...continues on next slide
CCSC:MW 2009,Saint Xavier University
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++;
}
ball.move(dx,dy);
pause(PAUSE_TIME);
}
CCSC:MW 2009,Saint Xavier University
Animation
Modify the bouncing ball demo to bounce an image around the
screen.
CCSC:MW 2009,Saint Xavier University
GPolygon
The GPolygon class can be used to represent closed polygonal
shapes.
Initially,a GPolygon 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).
GPolygons are resizable.
CCSC:MW 2009,Saint Xavier University
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);
}
}
CCSC:MW 2009,Saint Xavier University
Exercise:Diamonds
Create a program that draws randomly sized and colored diamonds
where clicked.
CCSC:MW 2009,Saint Xavier University
GCompound
GCompound objects are like canvases,you can add other GObjects
to them.
Some of GCompound's methods:
add(gobj)
Adds an object to this GCompound
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).
GCompound objects are resizable.
CCSC:MW 2009,Saint Xavier University
Make a face as a compound object
CCSC:MW 2009,Saint Xavier University
Exercise:Draw a house as a compound object
CCSC:MW 2009,Saint Xavier University
Turtles
The GTurtle class 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 specied number of degrees to the left
penDown()
Lowers the pen
penUp()
Raises the pen
right(angle)
Turns the specied 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)
showTurtle()
Makes the turtle visible
CCSC:MW 2009,Saint Xavier University
Fractals
GTurtle can be very useful for many types of graphics,especially
fractals.
The order 0 Koch snow ake is an equilateral triangle.The order n
Koch snow ake replaces each line of the order n 1 snow ake
with the following:
CCSC:MW 2009,Saint Xavier University
Fractals
CCSC:MW 2009,Saint Xavier University
Snow akes
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();
}
...continues on next slide
CCSC:MW 2009,Saint Xavier University
Snow akes
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);
}
}
...continues on next slide
CCSC:MW 2009,Saint Xavier University
Snow akes
public void run() {
zig(order,length);
turtle.right(120);
zig(order,length);
turtle.right(120);
zig(order,length);
turtle.right(120);
}
}
CCSC:MW 2009,Saint Xavier University
Exercise:Fractal
Make another fractal where the order 0 case is a square and the
order n case replaces each line of the order n 1 case with the
following:
Note that there are 8 segments in the production rule.
CCSC:MW 2009,Saint Xavier University
Fractals
CCSC:MW 2009,Saint Xavier University