[5010] in java-interest

home help back first fref pref prev next nref lref last post

Attempt at drawing movable rectangle

daemon@ATHENA.MIT.EDU (Jay Allen)
Thu Jan 25 20:45:06 1996

From: Jay Allen <kimberl1@gramercy.ios.com>
To: java-interest@java.sun.com
Date: Thu, 25 Jan 1996 19:11:05 -0500 (EST)

Hi all -

As part of my beginning self-instruction in Java, I wrote the following code which - 
theoretically - should create a rectangle which I can move around the screen at will. 

Here are my problems:

(1) The code doesn't even display the rectangle! What am I doing wrong? (The code is 
listed at the end of this message.)

(2) Am I implementing this correctly? Is this the best way to write this, or should I 
be using panels or some of the more advanced elements in the AWT?

Thanks for your responses in advance,

-J-

START CODE

/*
 * More experimentation
 * Create a rectangle which can be moved around freely by the user.
 * Jay Allen, January 24, 1996
 */

import java.applet.*;
import java.awt.*;

public class MoveRect extends Applet {

        protected int x, y, width, height;
        boolean goodDown;

        public void init() {
                x = 10;
                y = 10;
                width = 50;
                height = 50;
        }

        public boolean handleEvent(Event e) {
                // First check to see if this is a mouseclick. If so,
                // set goodDown to true if it's within the area of the
                // rect. If this event is a mouse drag, then move
                // the rect iff goodDown is true.

                if (e.id == Event.MOUSE_DOWN) {
                        if ((e.x > x && e.y > y) && (e.x < (x + width) && e.y < (x + 
height))) { 
                                goodDown = true;
                        } else {
                                goodDown = false;
                        }
                        return true;
                } else if (e.id == Event.MOUSE_DRAG && goodDown == true) {
                        if (e.x > x) {
                                x += e.x - x;
                        } else {
                                x -= x - e.x;
                        }
                        if (e.y > y) {
                                y += e.y - y;
                        } else {
                                y -= y - e.y;
                        }
                        repaint();
                        return true;
                } else if (e.id == Event.MOUSE_UP) {
                        goodDown = false;
                        return true;
                } else {
                        return false;
                }
                      
        }

        public void print(Graphics g) {
                g.drawRect(x, y, width, height);
        }
}
                        
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post