Java Usage of MouseListener and MouseMotionListnener #1

Part of the code is stolen from cited sources. In general, what is shown in blue is stuff generated by the IDE (not completely, however), and what is shown in black is my typing (I hope you know what I mean). I will annotate the text in color comments which should be self evident as to whether they are code or comments.
The code is far from perfect, since it doesn't make a clear distinction between clicking the mouse and hold the mouse button down, but that would complicate the structure too much right now.
 
/*
 * MouseTest.java
 *
 * Created on August 22, 2003, 1:17 PM
 */

/**
 *
 * @author  C. W. David
 * with some help from Cay Horstmann, Core Java
 * and Swing tutorials from SUN
 */

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;//added to get addWindowListener(this) to work
// after adding ScrollPane2

public class MouseTest extends javax.swing.JFrame implements WindowListener, MouseListener, MouseMotionListener{
    
    /** Creates new form MouseTest */
    public MouseTest() {
        initComponents();
        MyComponent figure = new MyComponent();
        jScrollPane1.add(figure);
        //the following are all required to get scrolling to take place:
        figure.setPreferredSize(new Dimension(600,600));
        jScrollPane1.setViewportView(figure);
        //end of scrolling required matters.
        //begin adding a hot spot
        rect1x = 20;
        rect1y = 20;
        rect1width = 100;
        rect1height = 50;//initialized here so we can change it if desired
        //                 and the same for the width and positions
        //end of hot spot
        int frameWidth = 400;
        int frameHeight = 400;
        this.setSize(frameWidth, frameHeight);
        this.setVisible(true);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */

    private void initComponents() {//GEN-BEGIN:initComponents
        jScrollPane1 = new javax.swing.JScrollPane();

        addWindowListener(this);

        jScrollPane1.addMouseListener(this);
        jScrollPane1.addMouseMotionListener(this);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pack();
    }

    // Code for dispatching events from components to event handlers.

    public void mouseClicked(java.awt.event.MouseEvent evt) {
    }

    public void mouseEntered(java.awt.event.MouseEvent evt) {
    }

    public void mouseExited(java.awt.event.MouseEvent evt) {
    }

    public void mousePressed(java.awt.event.MouseEvent evt) {
        if (evt.getSource() == jScrollPane1) {
            MouseTest.this.jScrollPane1MousePressed(evt);
        }
    }

    public void mouseReleased(java.awt.event.MouseEvent evt) {
    }

    public void mouseDragged(java.awt.event.MouseEvent evt) {
        if (evt.getSource() == jScrollPane1) {
            MouseTest.this.jScrollPane1MouseDragged(evt);
        }
    }

    public void mouseMoved(java.awt.event.MouseEvent evt) {
        if (evt.getSource() == jScrollPane1) {
            MouseTest.this.jScrollPane1MouseMoved(evt);
        }
    }

    public void windowActivated(java.awt.event.WindowEvent evt) {
    }

    public void windowClosed(java.awt.event.WindowEvent evt) {
    }

    public void windowClosing(java.awt.event.WindowEvent evt) {
        if (evt.getSource() == MouseTest.this) {
            MouseTest.this.exitForm(evt);
        }
    }

    public void windowDeactivated(java.awt.event.WindowEvent evt) {
    }

    public void windowDeiconified(java.awt.event.WindowEvent evt) {
    }

    public void windowIconified(java.awt.event.WindowEvent evt) {
    }

    public void windowOpened(java.awt.event.WindowEvent evt) {
    }//GEN-END:initComponents
    
    private void jScrollPane1MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane1MouseMoved
    
        // Add your handling code here:
        System.out.println("jScrollPane1MouseMoved");
        xpos = evt.getX();
        ypos = evt.getY();//get mouse position
        if (xpos > rect1x && xpos < rect1x+rect1width &&
        ypos > rect1y && ypos<rect1y + rect1height)
            rectActive = true;
        else
            rectActive = false;
        repaint();

    }//GEN-LAST:event_jScrollPane1MouseMoved
    
    private void jScrollPane1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane1MouseDragged
    
        // Add your handling code here:
        System.out.println("jScrollPane1MouseDragged");
        Point X = evt.getPoint();
        current = find(X.x, X.y);
        rect1x = X.x;
        rect1y = X.y;
        repaint();

    }//GEN-LAST:event_jScrollPane1MouseDragged
    
    private void jScrollPane1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane1MousePressed
    
        // Add your handling code here:
        System.out.println("jScrollPane1MousePressed");
        Point X = evt.getPoint();
        current=find(X.x,X.y);

/*here we check for a right click, indicating we want to remove, not add
a box.
*.

        if(javax.swing.SwingUtilities.isRightMouseButton(evt)){//could use import 
            if(current > -1)
                remove(current);
        }
        else
            if (current < 0){//not inside a square
                add(X.x,X.y);
            }

    }//GEN-LAST:event_jScrollPane1MousePressed
    
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        System.exit(0);
    }//GEN-LAST:event_exitForm
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        new MouseTest().show();
    }
    
    public void add(int x, int y){
        if (nsquares < MAXNSQUARES){
            squares[nsquares] = new Point(x,y);
            nsquares++;
            repaint();
        }
    }
    
    public void remove(int n){
        nsquares--;
        squares[n] = squares[nsquares];
        if(current == n) current = -1;
        repaint();
    }
    
    public int find(int x, int y ){
        for (int i =0;i<nsquares;i++)
            if(squares[i].x <=x && x<=squares[i].x+SQUARELENGTH && squares[i].y <=y && y<=squares[i].y+SQUARELENGTH)
                return i;
        return -1;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    
    private static final int SQUARELENGTH = 10;
    private static final int MAXNSQUARES = 100;
    private Point[] squares = new Point[MAXNSQUARES];
    private int nsquares = 0;
    private int current = -1;
    public int xpos,ypos,rect1x,rect1y,rect1width,rect1height;
    public boolean rectActive;
  
    class MyComponent extends JComponent{
        public void paint(Graphics g){
            Graphics2D g2d = (Graphics2D)g;
            super.paintComponent(g2d);//paint background, recommended by SUN

/*here we draw all the currently created boxes, depending on how many
clicks have been recorded
*/

            for (int i = 0; i<nsquares;i++)
                draw(g2d,i);
            //the following code shows how to make a "hot spot"
            if(rectActive)g2d.setColor(Color.GREEN);
            else g2d.setColor(Color.BLUE);

/*Here is the current upper left hand corner of the "active" box*/


            g2d.fillRect(rect1x,rect1y, rect1width, rect1height);

/*here we set the labelling color to print out the instantaneous value
of the x and y coordinate of the mouse at the instant
*/

            g2d.setColor(Color.BLUE);
            g2d.drawString("("+xpos+","+ypos+")",xpos,ypos);//moving position indicator
        }
        public void draw(Graphics g, int i){
            int xpos = squares[i].x;
            int ypos = squares[i].y;
            g.drawRect(xpos,ypos, SQUARELENGTH, SQUARELENGTH);

/*this is the static position of the box just drawn*.

            g.drawString("("+xpos+","+ypos+")",xpos,ypos);/*position indicator
                                                            when box is drawn
             */
        }
        
    }
}

Return to the main book TOC.