I ended up skipping this project in "The Art and Science of Java" and went on to the next one and figured out what I was missing. I didn't realize I could use an IF statement to compare the references of the objects, such as IF (gobj = red) and change the colors that way. Anyway here is the new code that works for two colors. The books calls for 7 of them, but that is just an extension.
**Write a GraphicsProgram that creates GLabels for each of the color names RED,
ORANGE, YELLOW, GREEN, CYAN, BLUE, and MAGENTA, and then puts those labels up on
the screen in a random position and in a random color. It turns out to be difficult to
identify the color of such a label if the name says one thing, but its color is different.
Programmer: Mike Chase
Date: 8-23-2011
*
* Revision 1:
* -----------
* Modify the program you wrote in exercise 10 so that pressing the mouse button on
top of one of the GLabels temporarily resets its color to the one that matches its
name. Releasing the mouse button should choose a new random color for the label.
*/
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import acm.util.*;
import java.awt.event.*;
public class FunnyColorNames extends GraphicsProgram{
public void run(){
double width = getWidth();
double height = getHeight();
red = new GLabel("Red");
red.setColor(rgen.nextColor());
red.setFont("Helvetica-24");
red.move(rgen.nextDouble(0,width - red.getWidth()), rgen.nextDouble(red.getAscent(), height + red.getAscent()));
add(red);
blue = new GLabel("Blue");
blue.setColor(rgen.nextColor());
blue.setFont("Helvetica-24");
blue.move(rgen.nextDouble(0,width - blue.getWidth()), rgen.nextDouble(blue.getAscent(), height - blue.getAscent()));
add(blue);
addMouseListeners();
}
// records mouse position to determine if null or GLabel is selected
public void mousePressed(MouseEvent e){
last = new GPoint(e.getPoint());
gobj = getElementAt(last);
println(last + " " + gobj);
if (gobj == red){
red.setColor(Color.RED);
} else if (gobj == blue){
blue.setColor(Color.BLUE);
}
}
public void mouseReleased(MouseEvent e){
if (gobj != null){
gobj.setColor(rgen.nextColor());
}
}
private RandomGenerator rgen = new RandomGenerator(); //creates random generated numbers and colors
private GObject gobj;
private GLabel red;
private GLabel blue;
private GPoint last;
}