Computer Science 225
Advanced Programming

Spring 2017, Siena College

DragAndDrop BlueJ Project

Click here to download a BlueJ project for DragAndDrop.


DragAndDrop Source Code

The Java source code for DragAndDrop is below. Click on a file name to download it.


DragAndDrop.java

import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 * Example DragAndDrop: dragging a little rectange around with
 * the mouse!
 *
 * @author Jim Teresco, Siena College, Computer Science 225, Spring 2017
 *
 */

public class DragAndDrop extends JApplet implements MouseListener, MouseMotionListener {

    /** position of the rectangle */
    private int x, y;

    /** am I currently dragging the rectangle? */
    private boolean dragging;
    
    /** remember mouse "grab point" in the rectangle */
    private int xOffset, yOffset;
    
    /** what color to draw the rectangle (it will change
     * based on the situation
     */
    private Color rectColor;
    
    /** rectangle's size */
    public static final int SIZE = 25;

    /**
     * init method for JApplet
     */
    public void init() {

        // initial position of our draggable rectangle
        x = 0;
        y = 0;

        addMouseListener(this);
        addMouseMotionListener(this);
    }

    /**
     * Applet's paint method to manage our graphics
     * 
     * @param g the Graphics reference
     */
    public void paint(Graphics g) {

        g.setColor(Color.white);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(rectColor);
        g.fillRect(x, y, SIZE, SIZE);
    }

    public void mouseClicked(MouseEvent e) {}

    public void mouseEntered(MouseEvent e) {}

    public void mouseExited(MouseEvent e) {}

    /** 
     * determine if the mouse was pressed in the bounds of
     * our rectangle.
     * 
     * @param e mouse event information
     */
    public void mousePressed(MouseEvent e) {

        dragging = (e.getX() >= x && e.getX() <= x + SIZE &&
            e.getY() >= y && e.getY() <= y + SIZE);
        xOffset = e.getX() - x;
        yOffset = e.getY() - y;
    }

    public void mouseReleased(MouseEvent e) {
    
        rectColor = Color.black;
        repaint();
    }

    public void mouseDragged(MouseEvent e) {
    
        if (dragging) {
            x = e.getX() - xOffset;
            y = e.getY() - yOffset;
            rectColor = Color.blue;
            repaint();
        }
    }

    public void mouseMoved(MouseEvent e) {
    
        if (e.getX() >= x && e.getX() <= x + SIZE &&
            e.getY() >= y && e.getY() <= y + SIZE) {
            rectColor = Color.red;
        }
        else {
            rectColor = Color.black;
        }
        repaint();
    }
}