CS 151 Lecture 10

Cover page image

Cay S. Horstmann

Lecture 10 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;

Lecture 10 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);

Lecture 10 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

Animations

  1. Copy all Java files from ~/oodp3code/ch04/animation file into your lab10 directory and make a project in that directory.
  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:

    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