CS 151 Day 8

Cover page image

Cay S. Horstmann

Day 8 Clicker Question 1

Consider this code:

TextField textField = new TextField("");
int DELAY = 1000;
ActionListener listener = event -> textField.setText("Hello...");
Timer t = new Timer(DELAY, listener);
// Add text field to frame and show frame

Assuming that textField is in a frame and the frame is shown in the usual way, what is the contents of the text field after 3 seconds;

  1. The code snippet cannot compile.
  2. The code compiles but nothing is shown.
  3. Hello...
  4. Hello...Hello...Hello...

Day 8 Clicker Question 2

What does this set of instructions draw?

Ellipse2D.Double e = new Ellipse2D.Double(10, 10, 20, 20);
Rectangle2D.Double r = new Rectangle2D.Double(10, 30, 20, 20);
  1. A circle to the left and a rectangle to the right that touches it.
  2. A circle to the top and a rectangle to the bottom that touches it.
  3. A circle inside a rectangle.
  4. Something else.

Day 8 Clicker Question 3

Which of the following classes or interfaces are in the standard Java library (and not the library of the textbook)? Check all that apply.

  1. Icon
  2. ImageIcon
  3. ShapeIcon
  4. MoveableShape

Lab

lab

UI Actions

  1. Copy the ~/oodp3code/ch04/action/ActionTester.java file into your lab8 directory and make a project in that directory.
  2. Change the program so that one must click the buttons in the correct order (Hello, Goodbye, Hello, ...) Hint: JButton.setEnabled.
  3. Change the program so that the message is changed to Hello 1, Goodbye 1, Hello 2, and so on, incrementing with each button click.

Animations

  1. Copy all Java files from ~/oodp3code/ch04/animation file into your lab8 directory and refresh the Eclipse project..
  2. Change the program so that it can animate any number of MoveableShape objects. Test with two cars.
  3. Add a class BouncingBall that is also a MoveableShape. It should bounce up and down.

Moveable Icon

  1. Suppose we want a dog to move in our delightful suburban scene of moving cars and bouncing balls. It would be a true pain to draw a dog from lines and ellipses. We just want to move an image file such as this one:

    dog

    Why can't we just add an ImageIcon to the list of moveable shapes?
  2. Complete this class:
    public class MoveableIcon extends ImageIcon implements MoveableShape 
    {
       public MoveableIcon(String filename, int x, int y)
       {
          super(filename);
          this.x = x;
          this.y = y;
       }
    
       . . .
       
       private int x;
       private int y;
    }
    
  3. Add a new MoveableIcon("dog.png", 100, 0) to the list of moveable shapes and run the program. What happens?
  4. You probably made the dog move by incrementing x in the move method. Make it more real by randomly moving left and right:
    if (Math.random() < 0.5) ...
  5. Did you do this in a Dog class or by changing MoveableIcon.move? What would be better?

Discussion

discussion