Bouncing Ball Lab - Contents

laboredbumbaileySoftware and s/w Development

Jun 7, 2012 (5 years and 2 months ago)

474 views











1

B
ouncing Ball Lab


Contents

Bouncing Ball Lab

................................
................................
................................
................................
..........

1

Overview

................................
................................
................................
................................
........................

2

Setting Up

................................
................................
................................
................................
.......................

2

Add Resources

................................
................................
................................
................................
................

2

BoucingBall

................................
................................
................................
................................
....................

2

Package and I
mport Statements

................................
................................
................................
..................

3

Attributes

................................
................................
................................
................................
....................

3

Function Stubs

................................
................................
................................
................................
............

4

The Constuctor

................................
................................
................................
................................
...........

5

The setBall() Method

................................
................................
................................
................................
..

5

The setThread() Method

................................
................................
................................
.............................

5

The checkBall() Method

................................
................................
................................
.............................

6

The toggleImage() Method

................................
................................
................................
.........................

7

The paintComponent() Method

................................
................................
................................
..................

7

The deliverMessage() Method

................................
................................
................................
....................

8

The TestBall Class

................................
................................
................................
................................
..........

8

Test

................................
................................
................................
................................
.............................

9

View the Applet

................................
................................
................................
................................
..........

9

The BouncingBanner Class

................................
................................
................................
...........................
10

Add a New Java File

................................
................................
................................
................................
..
10

Add import Statements

................................
................................
................................
..............................
10

Add attributes

................................
................................
................................
................................
............
11

Add Method Stub

................................
................................
................................
................................
......
11

The init() method

................................
................................
................................
................................
.......
12

The start() method

................................
................................
................................
................................
.....
12

The stop() method
................................
................................
................................
................................
......
12

The run() method

................................
................................
................................
................................
.......
12

The paint() method

................................
................................
................................
................................
....
13

The setUpGUI() method

................................
................................
................................
............................
13

The addTB() method

................................
................................
................................
................................
.
13

The actionPerformed() method

................................
................................
................................
..................
14

Test

................................
................................
................................
................................
................................
14

The HTLM Page

................................
................................
................................
................................
........
15












2

Overview

This lab explores use of two classes, both of which contain threads.
One of the classes,
BouncingBall
, contains an anonymous inn
er class.


Setting
U
p

1.

Create a folder on your desktop and name it
B
ouncingBall
.

a.

Create a new Netbeans project
.

b.

Select
Java Class Library as the project type.

c.

Name
t
he

proje
c
t

B
ouncing
.


d.

Save it to the
BouncingBall

folder.


2.

Add a class named
BouncingBall

and
p
lace it in
a
package

name
bouncingball
.

Add Resources

1.

Copy the
smiley_cirlce.
png file to the
c
lass

directory.


2.

Note that if you place this in the package directory, the
BouncingBall

object will not
be able to find it.

Boucing
Ball

BoucingBall is a class that allows you to animate either a
n image obtained from
a
file you
load from an external source or a
graphical image that you create using methods from the
Graphi
c2D class.











3


Package and Import Statements

1.

A
t the top of the
Bouncin
g
Ball

file

following the package statement
,
a
dd

the
followin
g
import

statement
s
. Note that the package statement is already in the file.

package bouncingball;

import java.awt.*;

import java
.util.*;

import javax.swing.*;

import java.awt.geom.*;

import java.util.Random;

2.

Alter the declaration of the class so that it assumes the following form:

public class BouncingBall extends
JPanel
{

}

Attributes

1.

Add the following attributes to the
BouncingBall

file
:


// Width and height of the container box


private int BOX_WIDTH = 400;


private int BOX_HEIGHT = 1
50;


// Controlling the refresh


// Number of updates per second


private static final int UPDATE_RATE = 27;


// in milliseconds


private static final long UPDATE_PERIOD = 1000L / UPDATE_RATE;


// Ball


// Ball's center (x, y)


pri
vate float ballX, ballY;


// Ball's speed for x and y


private float ballSpeedX, ballSpeedY;


// Ball's radius


private int ballRadius = 20;


private Image image;


//Image size


private final int IMX = 40, IMY = 40;











4


private Boolean motionStatus = true;


private Boolean showImage = true;


String message = new String();


ArrayList<String> messages = new ArrayList<String>();


Random rand = new Random(messages.size());

2.

Format your code.

Function Stubs


1.

Following th
e attributes, a
dd the following function stubs to the BouncingBall
class definition:


public BouncingBall(Image img, int
bw, int bh) {



}



private void setBall() {




}



private void setThread() {


}



private void checkBall() {



}



public String getMessage() {


return message;


}



public void setMessage(String msg) {


message = msg;


}



public void toggleImage() {



}



/** Custom drawing codes */


public void paintComponent(Graphics g) {



}











5



public String deliverMessage() {



return new String("");


}

The Constuctor

1.

Add the following code to the

constructor
:


image = img;


BOX_WIDTH = bw;


BOX_HEIGHT = bh;


setBall();


setThread();

2.

Format your code.

The
set
Ball
()

M
et
hod

1.

Add the following code to the
set
Ba
ll

() method:


// Generate a ball at a random location and moveAngle.


Random rand = new Random();


// Ch
oose (x, y) randomly but contained in the box


ballX = rand.nextInt(BOX_WIDTH
-

ballRadius * 2) + ballRadius / 2;


ballY = rand.nextInt(BOX_HEIGHT
-

ballRadius * 2) + ballRadius / 2;


// 0 to 359


int ballMoveAngle = rand.nextIn
t(360);


// 5 to 10


float ballSpeed = rand.nextInt(11);


ballSpeedX = (float) (ballSpeed * Math.cos(


Math.toRadians(ballMoveAngle)));


ballSpeedY = (float) (ballSpeed * Math.sin(


Math.toRadians(ballMoveAngle)));

2.

Format your code.

The setThread() Method

1.

Add the following code to the
setThread
()

method:


// Start the ball bouncing (in its own thread)











6


Thread ballThread = new Thread() {



public void run() {


while (true) {


// Refresh the display



checkBall();


repaint(); // Callback paintComponent()


// Delay for timing control and


// give other threads a chance


try {


Thread.sleep
(UPDATE_PERIOD);


} catch (InterruptedException ex) {


}


}


}


};


ballThread.start();


2.

Format your code.

The che
ckBall()

M
et
hod

1.

Add the following code to the
che
ckBall

() method:


ballX += ballSpeedX;


ballY += ballSpeedY;


if (ballX
-

ballRadius <
0) {


// Reflect along normal


ballSpeedX =
-
ballSpeedX;


// Re
-
position the ball at the edge


ballX = ballRadius;


setMessage(deliverMessage());


} else if (ballX + ballRadius > BOX_WIDTH) {



ballSpeedX =
-
ballSpeedX;


ballX = BOX_WIDTH
-

ballRadius;


setMessage(deliverMessage());


} else if (ballY
-

ballRadius < 0) {


ballSpeedY =
-
ballSpeedY;


ballY = ballRadius;











7


setMessage(deliverMessage());


} else if (ballY + ballRadius > BOX_HEIGHT) {


ballSpeedY =
-
ballSpeedY;


ballY = BOX_HEIGHT
-

ballRadius;


setMessage(deliverMessage());


}


2.

Format your code.

The
toggleImage()

M
et
hod

1.

Add the following code to the
toggleImage

() method:


if (showImage) {



showImage = false;


} else if (!showImage) {


showImage = true;


}

2.

Format your code.

The paintComponent() Method

1.

Add the following code to the
paintComponent

() method:

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;



// Draw the box


g2d.setColor(Color.blue);


g2d.fillRect(0, 0,

BOX_WIDTH, BOX_HEIGHT);


if (!showImage) {


// Draw the ball


g2d.setColor(Color.red);


g2d.fillOval((int) (ballX
-

ballRadius),


(int) (ballY
-

ballRadius),


2 * ballRadius, 2

* ballRadius);


} else {


/* The image must be shifted so that its center


* will correspond to that of the grapical object.











8


* This makes it collide with


* the borders in the rigth way */


AffineTransform affineTransform =


AffineTransform.getTranslateInstance(
-
IMX / 2,
-
IMY / 2);


g2d.transform(affineTransform);


g2d.drawImage(image, (int) ballX, (int) ballY, IMX, IMY, null);


}

2.

Format your code.

The deliverMessage() Method

1.

D
elete the starter code in the
deliverMessage()

methjod.

2.

Add
the following code to the

deliverMessage
()

method:



messages.add("Wow!");


messages.add("Pow!");


messages.add("Ow!");


messages.add("Now!");


int nextInt = rand.nextInt(messages.size());


String mes = messages.get(nextInt);


return mes;

3.

Format your code.

The TestBall Class

1.

Add a new class to your project.

Name it
TestBall

and place it in the bouncingball
package.

2.

R
eplace the code in the
TestBall

file with the follo
wing:

import java.awt.*;

import java.util.*;

import javax.swing.*;

import java.awt.geom.*;

import java.util.Random;


public class TestBall extends JApplet {



Image image;











9


BouncingBall bouncerPanel;




public void init(){


image = getImage(getCodeBase(), "smiley_circle.png");


bouncerPanel = new BouncingBall(image, 400, 150);


add(bouncerPanel);


}

}

Test

1.

Run the
TestBall clas.

2.

You see the Applet Viewer. The smiley face bounces
around it.

Note
that

the ball
will move at different speeds
depending

on the random numbers that have been
generated when
the BouncingBall object

is
c
onstructed
.


View the Applet

1.

Locate the web page for TestBall.

2.

Verify that it appears as follows:











10


The BouncingBanner Class

T
he

Bouncing
Banner class

allows you to make use of a few of the methods provided by
the BouncingBall class. To do so, it is nece
ssary to provide the class with a thread. The
threa
d allows the class to sample the state of the BouncingBall object.


Add a New Java File

1.

I
n the
bouncingball

package, add a new Java class called
B
ouncingBanner
.

2.

Replace the signature line of the class definition with the following code:

public class BouncingBanner extends JApplet


implements ActionListener, Runnable {

3.

Format you code. Note at
this

point

that NetBeans alerts you
that

the
run()

and
actionPerformed()

methods have not been added to the class definition.

Add
i
mport

Statements

1.

A
dd the following code to
the top of
your file

prior to the
opening

line of the class
def
i
nition
. Note that the i
mport statement already has been added.

package bouncingball;

import javax.swing.*;











11

import java.awt.*;

import java.awt.event.*;

import java.util.ArrayList;

import java.util.Random;

2.

Format your code.

Add attributes

1.

Add the following attributes to your class
definitio
n. These are placed after the
opening brace of the class.


Thread fThread;


JButton resetBtn;


JTextField msgTxt;


Image image;


Container lowerContainer, contentPane;


BouncingBall bouncerPanel;

2.

Format your code.

Add Method Stub

1.

Add the
following

method stubs to the class definition:


public void init() {


}



public void start() {


}



public void stop() {


}



public void run() {


}



public void paint(java.awt.Graphics g) {


}



private void setUpGUI() {











12


}



private void addTB() {


}



public void actionPerformed(ActionEvent ae) {


}//end ActionPerforme

2.

Format your code.

3.

Note that the warnings
concerning

the
run() and actionPerformed() methods
disappea
r.

T
he

i
nit
()

method

1.

Add the following code to the init() method:


image = getImage(getCodeBase(), "smiley_circle.png");


bouncerPanel = new BouncingBall(image, 400, 150);


setUpGUI();

2.

Format your code.

T
he

s
tart
()

method

1.

Add the following code to the init() method:


fThread = new Thread(this);


fThread.start();

2.

Format your code.

T
he

s
top
()

method

1.

Add the following code to the init() method:


if (fThread != null) {


fThread = null;


}

2.

Format your code.

T
he

r
un
()

method

1.

Add the following code to the init() method:











13


while (fThread != null) {


repaint();


// Pause


try {


Thread.sleep(20);


} catch (InterruptedException e) {


}


}

2.

Format your code.

T
he

p
aint
()

method

1.

Add the following code to the init() method:


if(msgTxt!=null){


msgTxt.setText(bouncerPanel.getMessage());


}

2.

Format your code.

T
he

s
etUpGUI
()

method

1.

Add the following code to the init() method:


contentPane = getContentPane();


contentPane.setLayout(new BorderLayout());


JPanel wpanel = new JPanel();


JPanel epanel = new JPanel();


contentPane.add(wpanel, BorderLayout.WEST);


contentPane.add(epanel, BorderLayout.EAST);


contentPane.add(b
ouncerPanel, BorderLayout.CENTER);


addTB();

2.

Format your code.

T
he

a
ddTB
()

method

1.

Add the following code to the init() method:


lowerContainer = new Container();


lowerContainer.setLayout(new FlowLayout());











14



//Create a text field


msgTxt = new JTextField("0.0");


msgTxt.setPreferredSize(new Dime
nsion(100, 30));


msgTxt.setFont(new Font("Dialog", 1, 14));



// Create a button


resetBtn = new JButton("Gr/Img");


resetBtn.setFont(new Font("Dialog", 1, 14));


resetBtn.setPreferredSize(new Dimension(100, 30));



resetBtn.addActionListener(this);



lowerContainer.add(resetBtn);


lowerContainer.add(msgTxt);


contentPane.add(lowerContainer, BorderLayout.SOUTH);

2.

Format your code.

T
he

a
ctio
nPerformed
()

method

1.

Add the following code to the init() method:


if (ae.getSource() == resetBtn) {


bouncerPanel.toggleImage();



}

2.

Format your code.

Test

1.

Run your cod
e.

2.

At first, you see the image of th
e smiling face.

The words in the text field
change

as
the image collides with the borders.

Since the words are randomly generated, they do
not always changed. (However, there is a way to fix this.)











15


3.

Click the button. You then see a
graphic
al image.


The HTLM Page

1.

Open the BouncingBanner.html file for editing.

2.

Change value ass
igned to the width
attribut
e to 400.

3.

Save and view th
e page.











16