MysteryProgram


Your browser is ignoring the <APPLET> tag!

This program draws a rectangle with a ball inside of it. The user can drag the ball but the ball is not able to leave the rectangle.

import objectdraw.*;

public class MysteryProgramController extends WindowController
{
    private static final int MARGIN = 15;
    
    private FramedRect box;
    private MysteryBall ball;
    
    private boolean ballGrabbed = false;
    private Location lastPoint;
    
    public void begin() {
       box = new FramedRect (MARGIN, MARGIN, 
                        getWidth() - 2*MARGIN, getHeight() - 2*MARGIN, 
                        canvas);
       ball = new MysteryBall (MARGIN, getWidth() - MARGIN, 
                                 MARGIN, getHeight() - MARGIN,
                                 canvas);
    }
    
    public void onMousePress(Location point) {
        if (ball.contains(point)) {
            ballGrabbed = true;
            lastPoint = point;
        }
    }
    
    public void onMouseDrag (Location point) {
        if (ballGrabbed && box.contains(lastPoint)) {
            double dx = point.getX() - lastPoint.getX();
            double dy = point.getY() - lastPoint.getY();
            ball.move (dx, dy);
            lastPoint = point;
        }
        else {
            ballGrabbed = false;
        }
    }
    
    public void onMouseRelease (Location point) {
        ballGrabbed = false;
    }
}

import objectdraw.*;

public class MysteryBall
{
    // The diameter of the ball
    private static final int BALL_SIZE = 20;
    
    // The ball's shape
    private FilledOval ball;
    
    private int leftEdge;
    private int rightEdge;
    private int topEdge;
    private int bottomEdge;
    
    public MysteryBall (int left, int right, int top, int bottom, DrawingCanvas canvas) {
        leftEdge = left;
        rightEdge = right;
        topEdge = top;
        bottomEdge = bottom;
        
        ball = new FilledOval (left, top, BALL_SIZE, BALL_SIZE, canvas);
    }
    
    public void move (double dx, double dy) {
        if (ball.getX() + dx < leftEdge) {
            dx = leftEdge - ball.getX();
        }
        
        else if (ball.getX() + dx + BALL_SIZE > rightEdge) {
            dx = rightEdge - ball.getX() - BALL_SIZE;
        }
        
        if (ball.getY() + dy < topEdge) {
            dy = topEdge - ball.getY();
        }
        
        else if (ball.getY() + dy + BALL_SIZE > bottomEdge) {
            dy = bottomEdge - ball.getY() - BALL_SIZE;
        }
       
        ball.move (dx, dy);
    }
    
    public boolean contains (Location point) {
        return ball.contains (point);
    }
}