What We Will Cover
Illuminations
Questions from last week or the Reading?
Midterm Questions?
- Has anyone NOT completed the second midterm yet?
- Midterm policy
- Grade calculation spreadsheet in Blackboard
- Tutoring resources
- How do you make a program with problems compile?
Homework Questions?
^ top
11.1: Reviewing Ants
Learner Outcomes
At the end of the lesson the student will be able to:
- Describe what is meant by the term "simulation"
- Write code to use the
Random class of the Java API
- Write code to display a Gaussian distribution in two dimensions
|
^ top
11.1.1: About Simulations
- This week we get to explore an exciting topic: computer simulations
- A computer simulation is a program that imitates or models a particular system
- Simulations are used for many things, from training aircraft pilots to scientific modeling
- With simulations we can:
- Better understand the system we simulate
- Predict what will happen in the future
- These two capabilties make simulations a very powerful tool
- As an example, we worked with a simple physics simulation in lesson 7 (chapter 6)
- The simulation was too simple to accurately predict planteary motion very far into the future
- However, the simulation helped us to undersand how gravity interacts with objects in a planetary system
- Before we continue, lets review some key concepts from the chapter
Concept Review
- Simulation: an imitation of some real thing or process.
- Computer simulation: a program that imitates or models a particular system.
- Pheromone: chemical signals that trigger a social response in members of the same species.
- Gaussian distribution: the normal distribution where values cluster around a mean value.
- Emergent behavior: the way complex behavior arises out of many simple interactions.
Check Yourself
- Of the following, ________ is NOT an example of a simulation.
- a device that artifically re-creates aircraft flight
- a computer model of the solar system
- driving your car to school
- weather prediction
- True or false: a computer simulation is a simulation that runs on a computer.
- True or false: pheromones are chemicals used by some insects species to trigger behavior such as following a food trail.
- True or false: a Gaussian distribution is another term for normal distribution.
- True or false: it is possible for computer systems to have behaviors that are not directly traceable to specific objects, but rather to the interaction of objects.
^ top
11.1.2: Setting up the Formicarium
- A formicarium is an enclosed area used for studying ant colonies
- Some people may call this an ant f__m simulation
- However, we cannot use the word ant and the word farm next to each other because the term is trademarked by Uncle Milton Toys, Inc.
- Evidently, their lawyers send letters people who use the term "generically" (see here)
- One person who was harassed by the lawyers was Scott Adams, the creator of Dilbert
- He received threatening letters for using "the words" in a Dilbert comic strip
- To resolve the issue, he was forced to write a clarification
Studing Ants
- Ants are particularly good at foraging for food
- Scientists study the behavior of ants and other insects to understand their successful strategies
- Finding good strategies can help solve engineering problems in human societies, like:
- Computer networks
- Routing cell phone signals
- Transmitting electricity efficiently
- Traffic systems
- Insects are somewhat machine-like and successful insect strategies can often be implemented on computers
Ants Scenario
Reviewing the Scenario
- At this point in the development, the ants wander around looking for food
- When an ant finds food, it brings the food back to its ant hill
- The
Creature class contains the methods for ant movement
- The class contains a
deltaX, deltaY pair used to calculate how far to move creatures
- It solves many of the problems of how to move creatures:
randomWalk(): move in random directions and speeds
headTowards(actorObj): move toward another Actor object
walk(): change locations based on deltaX and deltaY
- We will look at movement methods in more detail in the next section
Food Collection Efficiency
- As we run the scenario, look at how long it takes the ants to collect all the available food
- The search for food is completely random and the ants do not remember where they get food
- In the future we will look at how ants improve the efficiency of the food collection
Check Yourself
- Two words commonly used for a formicarium are ________ ________.
- Studying ant behavior has applications in ________.
- routing computer networks
- transmitting electicity more efficiently
- improving traffic systems
- all of these
- True or false: the purpose of the
Creature class is to contain common methods for creatures in the simulation.
More information
^ top
11.1.3: Moving Towards an Object
- One problem we often run into in games and simulations is moving an actor towards another actor
- This scenario solves the problem in several ways:
headTowards(target): adjust the walking direction towards a target actor
walkAwayFromHome(): walk away from the home ant hill
walkTowardsHome(): walk towards the home ant hill
- All the methods work in a similar way
- We will look at
headTowards(target) since it is a more general method
Moving Towards Another Actor
- To head towards another actor, we first get the (x, y) location of the target actor
- We then get (x, y) location of the object we want to move towards and subtract the two:
deltaX = target.getX() - getX();
deltaY = target.getY() - getY();
- This gives us the two components to calculate the direction of our movement vector

- We need to limit our movement to our maximum speed, for which we use
if-statements like:
if (deltaX > SPEED) {
deltaX = SPEED;
}
if (deltaY > SPEED) {
deltaY = SPEED;
}
- After limiting the speed, we set our new location
setLocation(getX() + deltaX, getY() + deltaY);
- Note that after we calculate the vector for moving towards an actor, it is easy to reverse direction and move away
- To move away, we simply subtract
deltaX and deltaY from our current location
Algorithm for Moving Towards Another Object
- Calculate the
deltaX between this object and the target object
- Calculate the
deltaY between this object and the target object
- Limit the
deltaX so it does not exceed the maximum allowed speed
- Limit the
deltaY so it does not exceed the maximum allowd speed
- Set the location of the object as (
x + deltaX, y + deltaY)
Methods headTowards(), capSpeed() and walk() of Creature
public void headTowards(Actor target)
{
deltaX = capSpeed(target.getX() - getX());
deltaY = capSpeed(target.getY() - getY());
}
private int capSpeed(int speed)
{
if (speed < -SPEED)
return -SPEED;
else if (speed > SPEED)
return SPEED;
else
return speed;
}
public void walk()
{
setLocation(getX() + deltaX, getY() + deltaY);
setRotation((int) (180 * Math.atan2(deltaY, deltaX)
/ Math.PI));
}
Check Yourself
- True or false:
deltaX and deltaY are the x- and y-components of the distance between two locations.
- To calculate
deltaX, ________ the current location from the target location.
- To limit the length of a movement vector, we use an ________ statement with a test condition comparing the speed to a maximum speed.
- True or false: to move an actor you change its location.
- Enter the code to move an actor based on
deltaX and deltaY.
^ top
11.1.4: Gaussian Distributions
Distribution of Food Crumbs
 |
 |
| Uniform distribution |
Gaussian distribution |
Random Distributions
- Many random number generators produce a distribution that is uniform
- The chance of every possible number is the same
- A Gaussian random number generator produces a normal distribution
- An application like a dice game or card game needs a uniform distribution
- We want every roll of a die or draw of a card to have the same chance
- However, if we want to model dropping crumbs on the ground we need a normal distribution
- Crumbs dropped on the ground normally center around a central point
- Dropping crumbs follows the normal distribution's 68-95-99.7 rule where:
- About 68% of observations fall within 1 standard deviation of the mean
- About 95% of observations fall within 2 standard deviations of the mean
- About 99.7% of observations fall within 3 standard deviations of the mean
- We can see these standard deviations and percentages in the following diagram
Normal Distribution

Check Yourself
- Another term for a Gaussian distribution is __________ distribution.
- When we want random numbers to simulate rolling dice, we need a(n) __________ distribution.
- Besides dropping crumbs on the ground, what other common phenomena follow normal distributions?
- Age of populations
- Physical measurements like height and weight
- Test scores
- Time people spend playing video games
- To capture 99.7% of a normal population we need __________ standard deviations about the mean.
^ top
11.1.5: Getting a Normally Distributed Random Number
Getting a Normal Random Coordinate
- The
nextGaussian() method returns a number between -infinity and +infinity
- However, 99.7% of the time the method will return a number between -3.0 and +3.0
- We need to convert the random number into a positive integer within the size of the food image
- A good strategy is to add a shifting value to the number returned
- In this case, we could add the number 3 to the number returned
3 + random.nextGaussian()
- What range of numbers do we usually get now?
Most of the time this will give us a positive number between 0 and 6
- We then divide by 6 to get a number between 0 and 1
(3 + random.nextGaussian()) / 6
- Now we need to scale the number to the size of the image
(3 + random.nextGaussian()) / 6 * size
- The variable
size is known as scaling the value
- To finish, we need to handle the 0.3% of the numbers we get outside the image size
- We can either limit the outliers to the image size or ignore them
- One solution is presented in the following method
- To call the method, we write code like:
x = randomCoordinate(img.getWidth() - 1);
y = randomCoordinate(img.getHeight() - 1);
Method randomCoordinate() of Class Food
private int randomCoordinate(int size) {
int coord = (int) ((3 + randomizer.nextGaussian())
/ 6 * size);
if (coord < 0)
{
coord = 0;
}
if (coord > size)
{
coord = size;
}
return coord;
}
Check Yourself
- The Java API class we use to get a Gaussian distribution is named ________.
- The
nextGaussian() method returns a negative number ________ the time.
- For the following code, ________ percent of the numbers output fall between
0.0 and 1.0.
(3 + randomizer.nextGaussian()) / 6
- For the above, ________ percent of numbers output will fall outside the range of
0.0 to 1.0.
- To scale a random number that is between 0.0 and 1.0, we ________ by the range we want.
^ top
Exercise 11.1
In this exercise, we add a cycle counter to the simulation.
Specifications
- Download the following file and save it in the scenario folder of Greenfoot.
Scenario file: ants-2b.zip.
- Start Greenfoot and open the scenario.
Greenfoot unzips the file for us.
- Open the
AntWorld class and add an import statement for a List:
import java.util.List;
- Also in the
AntWorld class, add a private instance variable named ticks of type Counter.
private Counter ticks = new Counter("Ticks:");
We will use this counter to measure food collection efficiency.
- In the constructor of
AntWorld, add the ticks variable to the world that you created in the previous step.
Compile the class and verify there are no errors. You should see the counter display on the screen at this step. Resolve any errors you find, getting help from a classmate or the instructor as needed.
- Add the following
act() method to AntWorld:

- Compile and run your scenario to verify all the changes work well.
If you have problems, ask a classmate or the instructor for help as needed.
- Run the scenario until all the food is gone. Write down the number of ticks counted until the food was collected.
We will compare this measurement of food collection efficiency with other measurements.
- Save a copy of your scenario as we will be adding to it in the next exercise.
Only submit the final scenario with all the lesson exercises completed, not the intermediate scenarios.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 11.1.6: Review.
^ top
11.1.6: Review
Answer these questions to check your understanding. You can find more information by following the links after the question.
- Which of the following is NOT an example of a simulation? (11.1.1)
- Artificial re-creation of aircraft flight
- A computer model of the solar system
- Driving a car
- Weather prediction
- True or false: a computer simulation is a simulation that runs on a computer. (11.1.1)
- True or false: pheromones are chemicals used by some insects species to trigger behavior such as following a food trail. (11.1.1)
- True or false: a Gaussian distribution is another term for normal distribution. (11.1.1)
- True or false: it is possible for computer systems to have behaviors that are not directly traceable to specific objects, but rather to the interaction of objects. (11.1.1)
- Two words commonly used for a formicarium are ________ _______. (11.1.2)
- What is one good reason to study ant behavior? (11.1.2)
- What is the purpose of the
Creature class? (11.1.2)
- What is the formula to calculate
deltaX and deltaY? (11.1.3)
- How do we limit the length of a movement vector? (11.1.3)
- When we want random numbers to simulate rolling dice, we need a(n) ______________ distribution. (11.1.4)
- When we want to simulate dropping crumbs on the, we need a(n) ______________ distribution. (11.1.4)
- How many standard deviations about the mean do we need to capture 99.7% of a normal population? (11.1.4)
- What Java API class do we use to get a Gaussian distribution? (11.1.5)
- How often do we get a negative number from the
nextGaussian() method? (11.1.5)
- For the following code, what percentage of the numbers output fall between
0.0 and 1.0? (11.1.5)
(3 + randomizer.nextGaussian()) / 6
- What percentage of numbers output from the above will fall outside the range of
0.0 and 1.0? (11.1.5)
- What technique do we use to scale a random number that is between 0.0 and 1.0 to a different range of values? (11.1.5)
^ top
11.2: Adding Pheromones
Learner Outcomes
At the end of the lesson the student will be able to:
- Implement pheromones in an ant colony simulation
- Describe a use of simulations in solving real life problems
- Discuss emergent behavior
|
^ top
11.2.1: Pheromones and the Search for Food
Dropping Phermones
- Each pheromone object represents a small drop of a chemical that ants leave on the ground
- An important property of pheromones is that each drop evaporates fairly quickly and then disappears
- Ants leave the pheremone drops when they return to the hill with a load of food
- When other ants smell the pheromones, they follow the trail of drops to the food
- By directing their search, food collection should be more efficient than random walking
Starting Class Pheromone
- Pheromones start out strong and fade fairly quickly
- We will need a variable to save the intensity of the pheromone
- Also, we will display the pheromone in our simulation using an image
- We will have our program draw the pheromone image as a circle
- Once we have some idea what our class will do, we add class
Pheromone to the simulation
Variables for Class Pheromone
private static final int MAX_INTENSITY = 180;
private int intensity;
Check Yourself
- Ants drop chemical signals known as __________ to tell other ants of a path to food
- True or false: pheromones evaporate and disappear over a short time.
- We can simulate the intensity of a pheromone using a(n) __________.
^ top
11.2.2: Drawing Pheromones
- Our ants are going to drop pheromones while returning to their home with food
- In our simulation, we will see the trail of pheromone drops as images
- We need to simulate phermones fading with time
- Our ants should find it harder to detect faded pheromone drops
- One way is to shrink the size of the image we display for the pheromone
- Ants are less likely to run into smaller images than larger images
- We can control the size of our pheromone image with our
intensity variable
- The following is one way to write the
updateImage() method
Method updateImage() of Class Pheromone
private void updateImage()
{
int size = intensity / 3 + 3;
GreenfootImage img = new GreenfootImage(size, size);
int alpha = intensity / 3;
img.setColor(new Color(255, 255, 255, alpha));
img.fillOval(0, 0, size, size);
setImage(img);
}
Transparency
Constructor of Class Pheromone
public Pheromone()
{
intensity = MAX_INTENSITY;
updateImage();
}
Fading Over Time
- With the image controlled by
intensity, we simply change the intensity in the act() method
- As you can see, we use the same recursive pattern we discussed in lesson 8.1.4
- Use an instance variable to control the intensity and give the variable a starting value
- Change the value of the intensity in the
act() method
- Test if the intensity has reached its goal with an
if-statement
Method act() of Class Pheromone
public void act()
{
intensity--;
if (intensity < 3)
{
getWorld().removeObject(this);
}
else
{
updateImage();
}
}
Manual Testing
- We can now manually test the
Pheromone class with: new Pheromone()
- As the scenario runs, the
Pheromone object fades away and disappears
Check Yourself
- When first displayed, the size of the pheromone image is ________ pixels square.
- For the pheromone to disappear, the intensity must be less than ________.
- The alpha value of a pheromone is ________ when it disappears.
- What code would we add to
updateImage() to show a small dot in the center of the image?
img.setColor(Color.BLACK);
img.fillOval(size / 2, size / 2, 2, 2);
^ top
11.2.3: Dropping the Pheromones
- Now that we have pheromones we need to get the ants to drop them
- Our ants should drop a pheromone only when carrying food as they move towards home
- Dropping a pheromone is a separate task so we should write a separate method
- We will need to call the new method from the
act() method
- We can see the method below and we can test the scenario to see how it works
Ant Method act() Calls dropPheromone()
public void act()
{
if (carryingFood) {
walkTowardsHome();
dropPheromone();
checkHome();
}
else
{
searchForFood();
}
}
private void dropPheromone() {
Pheromone ph = new Pheromone();
getWorld().addObject(ph, getX(), getY());
}
Tesing Pheromone Drops
Updated Method dropPheromone()
private void dropPheromone() {
pheromoneLevel++;
if (pheromoneLevel >= MAX_PH_LEVEL)
{
Pheromone ph = new Pheromone();
getWorld().addObject(ph, getX(), getY());
pheromoneLevel = 0;
}
}
Testing the Improvement
- When we test the scenario now we see the drops are spread out
- However, our ants do not follow the pheromone trail yet
- We will add this capability in the next section
Check Yourself
- True or false: separate tasks should be written in their own method.
- What are the three steps to controlling timing over multiple scenario cycles?
- Add an instance variable to hold counting values and intialize the variable
private int pheromoneLevel = 0;
- Change the value of the count in the
dropPheromone() method
pheromoneLevel++;
- Use an
if-statement to test if the count has reached its goal
if (pheromoneLevel >= MAX_PH_LEVEL)
- We set
pheromoneLevel = 0 after adding a pheromone to the world to ________ the count.
^ top
11.2.4: Following the Trail
- We need our ants to follow a pheromone trail
- If an ant smells a pheromone, it should first go the the center of the drop
- After reaching the center, the ant whould walk away from its home for some limited time
- Why should the ant walk away from home?
Pheromone drops are made in approximately a straight line from the food to home.
- Because of how the path was created, the ant is following the path to the source
- If the ant does not shortly smell a new pheromone drop or find food, it should revert to random walking
- The textbook provides the logic for following the path in the form of psuedocode
- After working out the logic of a method in psuedocode we translate the method into program code
Psuedocode for Following a Pheromone Trail
if (we recently found a drop of pheromone)
{
walk away from home;
}
else if (we smell pheromone now)
{
walk toward the center of the pheromone drop;
if (we are at the pheromone drop center)
{
note that we found pheromone;
}
}
else
{
walk randomly;
}
check for food;
- The logic of searching for food belongs in our
searchForFood() method
- However, we may need a few other helper methods to support searching for food
Method searchForFood(): Psuedocode Implemented
private void searchForFood()
{
if (foundLastPheromone > 0) {
foundLastPheromone--;
walkAwayFromHome();
}
else if (smellPheromone())
{
walkTowardsPheromone();
}
else
{
randomWalk();
}
checkFood();
}
Method smellPheromone()
public boolean smellPheromone()
{
Actor p = getOneIntersectingObject(Pheromone.class);
return (p != null);
}
Method walkTowardsPheromone()
public void walkTowardsPheromone()
{
Actor p = getOneIntersectingObject(Pheromone.class);
if (p != null) {
headTowards(p);
walk();
if (p.getX() == getX() && p.getY() == getY())
{
foundLastPheromone = PH_TIME;
}
}
}
Helper Methods
- Notice that the above methods help
searchForFood() perform its task
- Separarate tasks should each have their own methods
- Sometimes, one method needs another to perform its task more easily
- These methods that help other methods are known as helper methods
Check Yourself
- After working out the logic of a method in ________ we translate the method into program code
- The name of the variable used to control how long an ant walks away from home is ________.
- Why does walking away from home help an ant find the next pheromone drop or food? (answer)
- The method call in the above helper methods that checks for a collision is ________.
- When a method helps another method it is known as a ________ method.
^ top
11.2.5: Path Forming
- In nature, ants follow a phermone trail using their antennae to smell
- After following a path they are able to recognize and remember visual clues
- This makes traversing the path easier and faster than by using smell alone
- In the simulation, ants also follow the trail using the technique:
- Go to the center of the phernome drop
- Head away from home for a short time
- If another pheromene or food is not found then resume random walking
- Why does this work?
- Ants go directly home when they have food, dropping pheronomes along the way
- Thus, all pheromone drops are located directly between the food and home
- Also, the simulation has no obstacles that ants must go around
- With these simplifications, can we still learn about ants from our simulation?
Ant Colony Optimization Algorithms
- It turns out that ant behavior was the inspiration for a set of optimization techniques in computer science
- Ant colony optimization algorithms are a part of computer science studies known as swarm intelligence
- Ant colony algorithms have produced an optimal solution to classic computer problems such as the Traveling Salesman Problem
- The traveling salesman problem is about how to find the shortest distance between the cities on the route of a traveling salesman
- Solutions to the problem has applications in business such as for delivery vehicles
Emergent Behavior
- One interesting aspect of this simulation is that there is no code anywhere that talks about forming paths
- The programmed behavior of the individual ants is quite simple:
- If you have food go home while dropping pheromones;
- If you smell pheromones go away from home;
- Otherwise walk around randomly;
- However, together the ants display some sophisticated behavior
- They form stable paths, refreshing the pheromones as they evaporate
- Also, they efficiently transport food back to their ant hill
- This is known as emergent behavior
- The observed behavior is not programmed into an individual actor
- Instead, the behavior arises from the interaction of many simple actors
Efficiency of Food Collection
- With pheromones added, the efficiency of the food collection increases
- We will explore how much the efficiency increases in the next exercise
Check Yourself
- What aspects of the simulation regarding pheromone use are realistic and where have we made simplifications?
- True or false: ant behavior was the inspiration for solutions to computer problems that save businesses money on deliveries.)
- When complex behavior arises out of simple interactions, this is known as ________ behavior.
- How much improvement in food collection times do you think that adding pheromones produces, if any?
More Information
^ top
Exercise 11.2
In this exercise, we test the impact of adding pheromones to the ants search for food.
Specifications
- Start Greenfoot and open the scenario from the last exercise.
- If you are reinstalling the exercise, then download your
AntWorld.java file from Blackboard and save it in the unzipped scenario folder.
If you did not complete the last exercise, then you should do so now.
- Create a new subclass of actor named Pheromone, open the editor and copy this code to the new class.
Compile the class after copying in the code and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
- Open the
Ant class and add the following constants and instance variables:
private static final int MAX_PH_LEVEL = 18;
private int pheromoneLevel = 0;
private static final int PH_TIME = 30;
private int foundLastPheromone = 0;
Compile the class after copying in the code and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
- In the
Ant class and add the following methods:
private void dropPheromone() {
pheromoneLevel++;
if (pheromoneLevel >= MAX_PH_LEVEL)
{
Pheromone ph = new Pheromone();
getWorld().addObject(ph, getX(), getY());
pheromoneLevel = 0;
}
}
public boolean smellPheromone()
{
Actor p = getOneIntersectingObject(Pheromone.class);
return (p != null);
}
public void walkTowardsPheromone()
{
Actor p = getOneIntersectingObject(Pheromone.class);
if (p != null) {
headTowards(p);
walk();
if (p.getX() == getX() && p.getY() == getY())
{
foundLastPheromone = PH_TIME;
}
}
}
Compile the class after copying in the code and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
- In the
Ant class replace the act() method with the following:
public void act()
{
if (carryingFood) {
walkTowardsHome();
dropPheromone();
checkHome();
}
else
{
searchForFood();
}
}
Compile the class after copying in the code and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
- In the
Ant class replace the searchForFood() method with the following:
private void searchForFood()
{
if (foundLastPheromone > 0) {
foundLastPheromone--;
walkAwayFromHome();
}
else if (smellPheromone())
{
walkTowardsPheromone();
}
else
{
randomWalk();
}
checkFood();
}
- Compile and run your scenario to verify all the changes work well.
At this point your ants should drop phomones when they carry food and follow the pheromone trails when searching. If you have problems, ask a classmate or the instructor for help as needed.
- Run the scenario until all the food is gone. Write down the number of ticks counted until the food was collected.
We will compare this measurement of food collection efficiency with other measurements.
- Assume that pollution has introduced a toxic substance into the ant's environment, such that the time between dropping pheromones is 4 times as long. Change the
MAX_PH_LEVEL as follows and rerun the scenario until all the food is collected. Record the number of ticks counted for comparison with previous settings.
private static final int MAX_PH_LEVEL = 18 * 4;
- Restore the
MAX_PH_LEVEL setting and assume instead that another pollutant has decreased the ant's ability to remember when they smelled a pheromone. Instead of 30 steps they can only remember for 10 steps. Change the PH_TIME constant and rerun the scenario until all the food is collected. Record the number of ticks counted for comparison with previous settings.
private static final int PH_TIME = 30 / 3;
- Save your completed scenario to upload to Blackboard as part of assignment 9.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 11.2.6: Review.
^ top
11.2.6: Review
Answer these questions to check your understanding. You can find more information by following the links after the question.
- Ants drop chemical signals known as _____________ to tell other ants of a path to food (11.2.1)
- We can most easily simulate the intensity of a pheromone over time using: (11.2.1)
- an actor
- a chemical
- a variable
- a method
- Which of the following code statements add a small dot in the center of the
GreenfootImage variable named img? (11.2.2)
img.fillRect(size / 2, size / 2, 2, 2);
img.drawLine(size / 2, size / 2, 2, 2);
img.drawDot(size / 2, size / 2);
img.setcolorAt(size / 2, size / 2);
- True or false: images can change size as a scenario runs. (11.2.2)
- To make a single object disappear from a scenario, use the following code in the class for the object:
getWorld().removeObject(this);
getWorld().removeLastObject();
getWorld().removeObjects(getObjects(this));
removeFromWorld(anObject);
- True or false: images can change transparency as a scenario runs. (11.2.2)
- Which of the following is NOT part of controlling timing of multiple scenario cycles? (11.2.3)
- Declare and initialize a counter instance variable.
- Change the value of the counter in the
act() method.
- Use an
if-statement to test if the counter has reached its goal.
- Call the
setImage() method of the actor.
- Which of the following is a good reason to use a constant? (11.2.3)
- To document numbers
- To reduce code size
- To obfuscate numbers
- To use a
static variable
- True of false: separate tasks should be written in their own method. (11.2.3)
- Methods that help other methods do their job are known as ___________ methods. (11.2.4)
- True or false: psuedocode can show us the logic of a method. (11.2.4)
- True or false: to follow a pheromone path an ant needs to walk away from home. (11.2.4)
- True or false: a simulation mimics real world behavior exactly. (11.2.5)
- True or false: ant behavior was the inspiration for solutions to computer problems that save businesses money on deliveries. (11.2.5)
- When complex behavior arises out of simple interactions, this is known as __________________ behavior. (11.2.5)
^ top
11.3: Dialogs
Learner Outcomes
At the end of the lesson the student will be able to:
- Describe what is meant by a GUI
- Collect user input in an input dialog box
- Confirm information with a confirmation dialog
- Show messages using a message dialog
|
^ top
11.3.1: Foxes and Rabbits
Examining the Scenario
- The scenario is interesting and we looked at it during our homework
- However, the scenario has an extra feature not discussed in the textbook
- An extra window pops up and displays a graph
- The graph window is created by a
Plotter object
- The
Plotter object is constructed in the Field world in the usual way
- Looking at
Plotter in more detail, we see class types like JFrame and JLabel
JFrame and JLabel are part of the GUI somponent library that comes with Java
Graphical User Interfaces
- GUI is an acronym for Graphical User Interface
- Graphical User Interface (GUI) -- pronounced "gooey"
- Graphical: not just text or characters but includes windows, menus, buttons, etc.
- User: person using the program via mouse, keyboard, etc.
- Interface: interaction with the program using visual controls, widgets, etc.
- Note that Greenfoot uses some standard GUI components -- where are they?
- We will take a closer look at some GUI components in the following sections
Check Yourself
- GUI stands for G________ U________ I________.
- True or false: Java has a standard GUI libarary.
- What GUI components does Greenfoot itself use?
^ top
11.3.2: Java's GUI Libraries
- GUIs provide a graphical way to interact with a program
- The program presents information and users can enter information
- Users interact with GUI components using a mouse, keyboard or other input device
- Most modern applications use a GUI
- Typical graphical components include:
- Window: portion of screen providing an area for the other components
- Button: looks like a button that can be pressed
- Labels: Displays text or images in the window
- Text field: place where users can type values
- We can see the typical GUI components in the following image
Example GUI
Java's GUI Libraries
- GUIs are built from objects called components:
- Also called controls or widgets
- Java provides two sets of GUI components: AWT and Swing
- AWT (Abstract Window Toolkit) is the older set of components:
- Relies on the underlying visual components of the operating system
- AWT GUIs look different on every operating system
- Swing (like the dance) is the newer set of components:
- Extends AWT components and adds new capabilities
- Components draw their own visual shapes on the screen
- GUIs look about the same on every operating system
- The inheritance hierarchy below shows how Swing extends AWT
- Note that Swing components all start with the letter "J"
- As we can see, the GUI libraries are extensive with over 250 classes in Swing alone
- We will focus on only a small part in this lesson:
JDialog
Inheritance Hierarchy for GUI Components

Check Yourself
- True or false: Java has two GUI libraries: AWT and Swing.
- True or false: Swing components all start with the letter "S" (for Swing).
- True or false: Swing components extend AWT components.
^ top
11.3.3: User Dialogs
- Sometimes we need a user to enter information into our scenario
- For example, we want their name to add to a high score list
- Other times we may want to provide them with a help window
- One easy way to solve these problems is to use dialog boxes
Making a Dialog
Example Dialog Scenario
Method makeDialog() of Class Telephone
public void makeDialog()
{
inputStr = JOptionPane.showInputDialog(
"Hello, who is this?");
buttonNbr = JOptionPane.showConfirmDialog(
null, "Are you sure?");
String msg = "First name: " + inputStr
+ "\nButton number: " + buttonNbr
+ "\nPress OK or Enter key to exit.";
JOptionPane.showMessageDialog(null, msg);
}
Input Dialogs
Confirmation Dialogs
Message Dialogs
Commonly-Used Methods of JOptionPane
| Static Method |
Description |
| showConfirmDialog |
Asks a confirming question, like yes/no/cancel and returns an int number corresponding to the button pressed. |
| showInputDialog |
Prompts for user text input and returns a string containing the text entered by the user. |
| showMessageDialog |
Displays a message and waits until the user presses a button in confirmation. |
Check Yourself
- True or false: dialog boxes can be constructed using class
JOptionPane.
- True or false: dialogs can be created with a single statement.
- The type of data returned by the
showInputDialog() method is ________.
- The type of data returned by the
showConfirmDialog() method is ________.
^ top
11.3.4: Dialog Arguments
- Most methods of
JOptionPane that create dialogs are overloaded to provide display options
- These options control dialog placement, messages and icons displayed, and title-bar wording
- Both
showInputDialog() and showMessageDialog() accept the arguments listed in the table below
- For example, one method of
showInputDialog() can accept four arguments:
JOptionPane.showInputDialog(parentComponent, messageString,
titleString, messageTypeInt);
- To display a different dialog without an input field:
JOptionPane.showMessageDialog(parent, message);
- If the parent component is unknown, we use
null for that argument
JOptionPane.showMessageDialog(null, "Hello, world!");
- Note that we cannot use our main Greenfoot window as a parent compoent
- Thus, we normally use
null as the parent argument
- We can look up the exact usage for the various methods in the JOptionPane API documentation
Commonly-Used Arguments in JOptionPane Methods
| Argument |
Description |
| parentComponent |
An object representing the frame of the dialog box and controls its placement on the screen. If null is used, the dialog is centered on the screen. |
| messageString |
A descriptive message displayed in the dialog box. |
| titleString |
A title typically placed in the title bar above the dialog box. |
| messageTypeInt |
Indicates the type of icon to display in the dialog box. Choosing one of the message types shown below will display the corresponding icon. |
| icon |
Used if you want to display your own icon image rather than a built-in icon. |
Icons provided by JOptionPane
| Metal |
Windows |
Message Type |
Description |
 |
 |
ERROR_MESSAGE |
Displays an error icon. |
 |
 |
INFORMATION_MESSAGE |
Displays an information icon. |
 |
 |
WARNING_MESSAGE |
Displays an warning icon. |
 |
 |
QUESTION_MESSAGE |
Displays an question icon. |
| |
|
PLAIN_MESSAGE |
Does not display an icon. |
Check Yourself
- True or false: we can adjust the look of dialogs by changing arguments to the creation methods.
- True or false: we can set text in the title bar of a dialog.
- Enter a statement that creates an input dialog with the following options:
- A message that says, "Enter your name:".
- A title that says, "Winner".
- An icon that displays a question mark.
More Information
^ top
11.3.5: Adding Dialogs to a Greenfoot Scenario
- Let us look at how we can add dialogs to our scenario
Step-by-Step Procedure for Adding Dialogs
- The first step is to decide which class will conduct the dialog
- In our example, the class is named
Telephone
- The next step is to import
JOptionPane:
import javax.swing.JOptionPane;
- Set up a condition, usually in our
act() method, that starts the dialog
In our example, we used a mouse click:
if (Greenfoot.mousePressed(this)) {
// ...
makeDialog();
// ...
}
- Next, construct the sequence of dialog statements and save the user input we need
public void makeDialog()
{
inputStr = JOptionPane.showInputDialog(
"Hello, who is this?");
buttonNbr = JOptionPane.showConfirmDialog(
null, "Are you sure?");
String msg = "First name: " + inputStr
+ "\nButton number: " + buttonNbr
+ "\nPress OK or Enter key to exit.";
JOptionPane.showMessageDialog(null, msg);
}
Dialog Modality
- Note that dialogs are modal: they stop the scenario from running until the user finishes her input
- This is usually the behavior you want
- Why keep running a game while the user is looking at the instructions dialog?
- If we do not want modal behavior we will need a different approach
- We will look at more user input options later in the course
Check Yourself
- Import the ________ API library when using dialogs.
- True or false: a scenario stops running while a dialog is displayed and resumes when the dialog is closed.
- The reason to use an if-statement in the
act() method when creating a dialog is that the dialog ________ the scenario.
^ top
11.3.6: Project Dialog
- Over the next few weeks we will work on the final course project
- You have wide freedom in defining your project, though there are requirements to meet
- A project is a powerful way to develop a deeper understanding of programming
- You will work with many of the Java and Greenfoot features to develop your project
- At the end you will have created a program you can be proud of
- You will develop your project over four phases as shown below
- You will have about one week to complete each phase
Project Phases
- Project proposal: define what your project is about
- Initial prototype: find out if your core concepts work
- User-testable prototype: get suggestions from other students
- Final project: the final version (at least for this course)
^ top
Exercise 11.3
In this exercise, we explore the use of dialogs in Greenfoot.
Specifications
- Download the following file and save it in the scenario folder of Greenfoot.
Scenario file: dialogs.zip.
- Start Greenfoot and open the scenario.
Greenfoot unzips the file for us.
- Open the
Telephone class and locate the makeDialog() method.
We will use this method to create our dialogs.
- Change the first dialog to ask the user to enter a name.
Save the answer in the variable inputStr.
- Add another instance variable to the Telephone class, like:
private String codeStr;
- Add a second input dialog statement asking the user to enter a code and save the answer in the above variable.
For more information on input dialogs see section: 11.3.3: User Dialogs.
- Construct a message like the following:
String msg = "Your name is " + inputStr + " and the code is " + codeStr + ". \nIs this correct?";
- Show a dialog with the above message, and save the answer the user enters in the variable
buttonNbr.
For more information on confirmation dialogs see section: 11.3.3: User Dialogs.
- If the user pressed the No or Cancel button, then return from the method immediately.
Hint: buttons are numbered from left to right with the first button on the left being number 0.
- If the user entered the code "42" (without the quotation marks), then show a message dialog saying, "The meaning of life." Otherwise, show a message dialog saying, "Wrong code. Try entering the number 42."
For more information on message dialogs see section: 11.3.3: User Dialogs.
- Compile and run your scenario to verify all the changes work well.
If you have problems, ask a classmate or the instructor for help as needed.
- Save your
Telephone.java file to submit to Blackboard as part of assignment 9.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 11.3.7: Review.
^ top
11.3.7: Review
Answer these questions to check your understanding. You can find more information by following the links after the question.
- GUI stands for G___________ U_________ I___________. (11.3.1)
- True or false: Java has a standard GUI libarary. (11.3.1)
- What are three components typically used in GUIs? (11.3.2)
- True or false: Java has two GUI libraries: AWT and Swing. (11.3.2)
- True or false: Swing components all start with the letter "S" (for Swing). (11.3.2)
- True or false: Swing components extend AWT components. (11.3.2)
- True or false: dialog boxes can be constructed using class
JOptionPane. (11.3.3)
- What is the name of the method to create input dialogs? (11.3.3)
- What is the name of the method to create confirmation dialogs? (11.3.3)
- What is the name of the method to create message dialogs? (11.3.3)
- True or false: dialogs can be created with a single statement. (11.3.3)
- What type of data does the
showInputDialog() method return? (11.3.3)
- What type of data does the
showConfirmDialog() method return? (11.3.3)
- True or false: we can set text in the title bar of a dialog. (11.3.4)
- Write a statement that creates an input dialog with the following options: (11.3.4)
- A message that says, "Enter your name".
- A title that says, "Winner's name".
- An icon that displays a question mark.
- Which API library do you import when using dialogs? (11.3.5)
- True or false: a scenario stops running while a dialog is displayed and resumes when the dialog is closed. (11.3.5)
^ top
Wrap Up
Due Next: A8: Image Manipulation (4/25/12)
A9: Project Proposal (5/2/12)
- When class is over, please shut down your computer
- You may complete unfinished lesson exercises at any time before the due date.
^ top
Home
| Blackboard
| Schedule
| Syllabus
| Room Policies
Help
| FAQ's
| HowTo's
| Links
Last Updated: April 29 2012 @00:45:34
|