Java/Event/Mouse

Материал из Java эксперт
Перейти к: навигация, поиск

Detecting Double and Triple Clicks

  
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addMouseListener(new MyMouseListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
    component.addMouseListener(new MyMouseListener());
  }
}
class MyMouseListener extends MouseAdapter {
  public void mouseClicked(MouseEvent evt) {
    if (evt.getClickCount() == 3) {
      System.out.println("triple-click");
    } else if (evt.getClickCount() == 2) {
      System.out.println("double-click");
    }
  }
}





Drags within the image

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/*
 * SelectionDemo.java is a 1.4 application that requires one other file:
 * images/starfield.gif
 */
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
/*
 * This displays an image. When the user drags within the image, this program
 * displays a rectangle and a string indicating the bounds of the rectangle.
 */
public class SelectionDemo {
  JLabel label;
  static String starFile = "starfield.gif";
  private void buildUI(Container container, ImageIcon image) {
    container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
    SelectionArea area = new SelectionArea(image, this);
    container.add(area);
    label = new JLabel("Drag within the image.");
    label.setLabelFor(area);
    container.add(label);
    //Align the left edges of the components.
    area.setAlignmentX(Component.LEFT_ALIGNMENT);
    label.setAlignmentX(Component.LEFT_ALIGNMENT); //redundant
  }
  public void updateLabel(Rectangle rect) {
    int width = rect.width;
    int height = rect.height;
    //Make the coordinates look OK if a dimension is 0.
    if (width == 0) {
      width = 1;
    }
    if (height == 0) {
      height = 1;
    }
    label.setText("Rectangle goes from (" + rect.x + ", " + rect.y
        + ") to (" + (rect.x + width - 1) + ", "
        + (rect.y + height - 1) + ").");
  }
  /** Returns an ImageIcon, or null if the path was invalid. */
  protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = SelectionDemo.class.getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL);
    } else {
      System.err.println("Couldn"t find file: " + path);
      return null;
    }
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("SelectionDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Set up the content pane.
    SelectionDemo controller = new SelectionDemo();
    controller.buildUI(frame.getContentPane(), createImageIcon(starFile));
    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
  private class SelectionArea extends JLabel {
    Rectangle currentRect = null;
    Rectangle rectToDraw = null;
    Rectangle previousRectDrawn = new Rectangle();
    SelectionDemo controller;
    public SelectionArea(ImageIcon image, SelectionDemo controller) {
      super(image); //This component displays an image.
      this.controller = controller;
      setOpaque(true);
      setMinimumSize(new Dimension(10, 10)); //don"t hog space
      MyListener myListener = new MyListener();
      addMouseListener(myListener);
      addMouseMotionListener(myListener);
    }
    private class MyListener extends MouseInputAdapter {
      public void mousePressed(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        currentRect = new Rectangle(x, y, 0, 0);
        updateDrawableRect(getWidth(), getHeight());
        repaint();
      }
      public void mouseDragged(MouseEvent e) {
        updateSize(e);
      }
      public void mouseReleased(MouseEvent e) {
        updateSize(e);
      }
      /*
       * Update the size of the current rectangle and call repaint.
       * Because currentRect always has the same origin, translate it if
       * the width or height is negative.
       * 
       * For efficiency (though that isn"t an issue for this program),
       * specify the painting region using arguments to the repaint()
       * call.
       *  
       */
      void updateSize(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        currentRect.setSize(x - currentRect.x, y - currentRect.y);
        updateDrawableRect(getWidth(), getHeight());
        Rectangle totalRepaint = rectToDraw.union(previousRectDrawn);
        repaint(totalRepaint.x, totalRepaint.y, totalRepaint.width,
            totalRepaint.height);
      }
    }
    protected void paintComponent(Graphics g) {
      super.paintComponent(g); //paints the background and image
      //If currentRect exists, paint a box on top.
      if (currentRect != null) {
        //Draw a rectangle on top of the image.
        g.setXORMode(Color.white); //Color of line varies
        //depending on image colors
        g.drawRect(rectToDraw.x, rectToDraw.y, rectToDraw.width - 1,
            rectToDraw.height - 1);
        controller.updateLabel(rectToDraw);
      }
    }
    private void updateDrawableRect(int compWidth, int compHeight) {
      int x = currentRect.x;
      int y = currentRect.y;
      int width = currentRect.width;
      int height = currentRect.height;
      //Make the width and height positive, if necessary.
      if (width < 0) {
        width = 0 - width;
        x = x - width + 1;
        if (x < 0) {
          width += x;
          x = 0;
        }
      }
      if (height < 0) {
        height = 0 - height;
        y = y - height + 1;
        if (y < 0) {
          height += y;
          y = 0;
        }
      }
      //The rectangle shouldn"t extend past the drawing area.
      if ((x + width) > compWidth) {
        width = compWidth - x;
      }
      if ((y + height) > compHeight) {
        height = compHeight - y;
      }
      //Update rectToDraw after saving old value.
      if (rectToDraw != null) {
        previousRectDrawn.setBounds(rectToDraw.x, rectToDraw.y,
            rectToDraw.width, rectToDraw.height);
        rectToDraw.setBounds(x, y, width, height);
      } else {
        rectToDraw = new Rectangle(x, y, width, height);
      }
    }
  }
}





Handle mouse button click event?

  
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class Main extends JFrame {
  public Main() {
    setSize(300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JTextArea textArea = new JTextArea();
    textArea.setText("Click Me!");
    textArea.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        if (e.getButton() == MouseEvent.NOBUTTON) {
          textArea.setText("No button clicked...");
        } else if (e.getButton() == MouseEvent.BUTTON1) {
          textArea.setText("Button 1 clicked...");
        } else if (e.getButton() == MouseEvent.BUTTON2) {
          textArea.setText("Button 2 clicked...");
        } else if (e.getButton() == MouseEvent.BUTTON3) {
          textArea.setText("Button 3 clicked...");
        }
        System.out.println("Number of click: " + e.getClickCount());
        System.out.println("Click position (X, Y):  " + e.getX() + ", " + e.getY());
      }
    });
    getContentPane().add(textArea);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}





Handle mouse motion event

  
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class Main extends JFrame {
  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 400);
    JTextArea textArea = new JTextArea("drag it...");
    textArea.addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseDragged(MouseEvent e) {
        System.out.println("Mouse Dragged...");
      }
      public void mouseMoved(MouseEvent e) {
        System.out.println("Mouse Moved...");
      }
    });
    getContentPane().add(textArea);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}





Handling Mouse Clicks

  
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addMouseListener(new MyMouseListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyMouseListener extends MouseAdapter {
  public void mouseClicked(MouseEvent evt) {
    if ((evt.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
      System.out.println("left" + (evt.getPoint()));
    }
    if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
      System.out.println("middle" + (evt.getPoint()));
    }
    if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
      System.out.println("right" + (evt.getPoint()));
    }
  }
}





Handling Mouse Motion

  
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addMouseMotionListener(new MyMouseMotionListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyMouseMotionListener extends MouseMotionAdapter {
  public void mouseMoved(MouseEvent evt) {
    System.out.println("moved:" + evt.getPoint());
  }
  public void mouseDragged(MouseEvent evt) {
    System.out.println("dragged:" + evt.getPoint());
  }
}





InputEvent.BUTTON1_MASK (for left mouse button)

  
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addMouseListener(new MyMouseListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyMouseListener extends MouseAdapter {
  public void mouseClicked(MouseEvent evt) {
    if ((evt.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
      System.out.println("left" + (evt.getPoint()));
    }
    if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
      System.out.println("middle" + (evt.getPoint()));
    }
    if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
      System.out.println("right" + (evt.getPoint()));
    }
  }
}





InputEvent.BUTTON2_MASK (for middle mouse button)

  
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addMouseListener(new MyMouseListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyMouseListener extends MouseAdapter {
  public void mouseClicked(MouseEvent evt) {
    if ((evt.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
      System.out.println("left" + (evt.getPoint()));
    }
    if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
      System.out.println("middle" + (evt.getPoint()));
    }
    if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
      System.out.println("right" + (evt.getPoint()));
    }
  }
}





InputEvent.BUTTON3_MASK (for right mouse button)

  
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addMouseListener(new MyMouseListener());
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyMouseListener extends MouseAdapter {
  public void mouseClicked(MouseEvent evt) {
    if ((evt.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
      System.out.println("left" + (evt.getPoint()));
    }
    if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
      System.out.println("middle" + (evt.getPoint()));
    }
    if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
      System.out.println("right" + (evt.getPoint()));
    }
  }
}





Mouse drag and draw

  
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MouseDragActionPanel extends JPanel implements MouseMotionListener {
  private static final int SquareWidth = 10;
  private static final int Max = 100;
  private Rectangle[] squares = new Rectangle[Max];
  private int squareCount = 0;
  private int currentSquareIndex = -1;
  public MouseDragActionPanel() {
    addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent evt) {
        int x = evt.getX();
        int y = evt.getY();
        currentSquareIndex = getSquare(x, y);
        if (currentSquareIndex < 0) // not inside a square
          add(x, y);
      }
      public void mouseClicked(MouseEvent evt) {
        int x = evt.getX();
        int y = evt.getY();
        if (evt.getClickCount() >= 2) {
          remove(currentSquareIndex);
        }
      }
    });
    addMouseMotionListener(this);
  }
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (int i = 0; i < squareCount; i++)
      ((Graphics2D)g).draw(squares[i]);
  }
  public int getSquare(int x, int y) {
    for (int i = 0; i < squareCount; i++)
      if(squares[i].contains(x,y))
        return i;
    return -1;
  }
  public void add(int x, int y) {
    if (squareCount < Max) {
      squares[squareCount] = new Rectangle(x, y,SquareWidth,SquareWidth);
      currentSquareIndex = squareCount;
      squareCount++;
      repaint();
    }
  }
  public void remove(int n) {
    if (n < 0 || n >= squareCount)
      return;
    squareCount--;
    squares[n] = squares[squareCount];
    if (currentSquareIndex == n)
      currentSquareIndex = -1;
    repaint();
  }
  public void mouseMoved(MouseEvent evt) {
    int x = evt.getX();
    int y = evt.getY();
    if (getSquare(x, y) >= 0)
      setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    else
      setCursor(Cursor.getDefaultCursor());
  }
  public void mouseDragged(MouseEvent evt) {
    int x = evt.getX();
    int y = evt.getY();
    if (currentSquareIndex >= 0) {
      Graphics g = getGraphics();
      g.setXORMode(getBackground());
      ((Graphics2D)g).draw(squares[currentSquareIndex]);
      squares[currentSquareIndex].x = x;
      squares[currentSquareIndex].y = y;
      ((Graphics2D)g).draw(squares[currentSquareIndex]);
      g.dispose();
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("MouseTest");
    frame.setSize(300, 200);
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    Container contentPane = frame.getContentPane();
    contentPane.add(new MouseDragActionPanel());
    frame.show();
  }
}





MouseDragClip -- implement simple mouse drag in a window. Speed up by using clipping regions

  
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
////
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Label;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
/**
 * MouseDragClip -- implement simple mouse drag in a window. Speed up by using
 * clipping regions.
 * <p>
 * This version "works" for very simple cases (only drag down and to the right,
 * never move up or back :-) ).
 * 
 * @author Ian Darwin, http://www.darwinsys.ru/
 */
public class MouseDragClip extends Canvas implements MouseListener,
    MouseMotionListener {
  /** The Image we are to paint */
  Image curImage;
  /** Kludge for showStatus */
  static Label status;
  /** true if we are in drag */
  boolean inDrag = false;
  /** starting location of a drag */
  int startX = -1, startY = -1;
  /** current location of a drag */
  int curX = -1, curY = -1;
  /** Previous ending of current drag */
  int oldX, oldY;
  /** Start of previous selection, if completed, else -1 */
  int oldStartX = -1, oldStartY = -1;
  /** Size of previous selection, if completed, else -1 */
  int oldWidth = -1, oldHeight = -1;
  // "main" method
  public static void main(String[] av) {
    JFrame f = new JFrame("Mouse Dragger");
    Container cp = f.getContentPane();
    if (av.length < 1) {
      System.err.println("Usage: MouseDragClip imagefile");
      System.exit(1);
    }
    Image im = Toolkit.getDefaultToolkit().getImage(av[0]);
    // create a MouseDragClip object
    MouseDragClip j = new MouseDragClip(im);
    cp.setLayout(new BorderLayout());
    cp.add(BorderLayout.NORTH, new Label(
        "Hello, and welcome to the world of Java"));
    cp.add(BorderLayout.CENTER, j);
    cp.add(BorderLayout.SOUTH, status = new Label());
    status.setSize(f.getSize().width, status.getSize().height);
    f.pack();
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  /** Construct the MouseDragClip object, given an Image */
  public MouseDragClip(Image i) {
    super();
    curImage = i;
    setSize(300, 200);
    addMouseListener(this);
    addMouseMotionListener(this);
  }
  public void showStatus(String s) {
    status.setText(s);
  }
  // Five methods from MouseListener:
  /** Called when the mouse has been clicked on a component. */
  public void mouseClicked(MouseEvent e) {
  }
  /** Called when the mouse enters a component. */
  public void mouseEntered(MouseEvent e) {
  }
  /** Called when the mouse exits a component. */
  public void mouseExited(MouseEvent e) {
  }
  /** Called when the mouse has been pressed. */
  public void mousePressed(MouseEvent e) {
    Point p = e.getPoint();
    System.err.println("mousePressed at " + p);
    startX = p.x;
    startY = p.y;
    inDrag = true;
  }
  /** Called when the mouse has been released. */
  public void mouseReleased(MouseEvent e) {
    inDrag = false;
    System.err.println("SELECTION IS " + startX + "," + startY + " to "
        + curX + "," + curY);
    oldX = -1;
    oldStartX = startX;
    oldStartY = startY;
    oldWidth = curX - startX;
    oldHeight = curY - startY;
  }
  // And two methods from MouseMotionListener:
  public void mouseDragged(MouseEvent e) {
    Point p = e.getPoint();
    // showStatus("mouse dragged to " + p);
    curX = p.x;
    curY = p.y;
    if (inDrag) {
      repaint();
    }
  }
  /**
   * This update() overrides Component"s, to call paint() <I>without </I>
   * clearing the screen (which has our main image on it, after all!
   */
  public void update(Graphics g) {
    paint(g);
  }
  public void paint(Graphics g) {
    int w = curX - startX, h = curY - startY;
    Dimension d = getSize();
    if (!inDrag) { // probably first time through(?)
      g.drawImage(curImage, 0, 0, d.width, d.height, this);
      return;
    }
    System.err.println("paint:drawRect @[" + startX + "," + startY
        + "] size " + w + "x" + h);
    // Restore the old background, if previous selection
    if (oldStartX != -1) {
      g.setClip(oldStartX, oldStartY, oldWidth + 1, oldHeight + 1);
      g.drawImage(curImage, 0, 0, d.width, d.height, this);
      oldStartX = -1;
    }
    // Restore the background from previous motions of current drag
    if (oldX != -1) {
      g.setClip(startX, startY, w, h);
      g.drawImage(curImage, 0, 0, d.width + 1, d.height + 1, this);
    }
    // Draw the new rectangle
    g.setClip(0, 0, d.width, d.height);
    g.setColor(Color.red);
    g.drawRect(startX, startY, w, h);
    oldX = curX;
    oldY = curY;
  }
  /**
   * Invoked when the mouse moves; just update the status line with the new
   * coordinates.
   */
  public void mouseMoved(MouseEvent e) {
    showStatus("[" + e.getPoint().x + "," + e.getPoint().y + "]");
  }
}





MouseDrag -- implement simple mouse drag in a window

  
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Label;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
/**
 * MouseDrag -- implement simple mouse drag in a window.
 */
public class MouseDrag extends Component implements MouseListener,
    MouseMotionListener {
  /** The Image we are to paint */
  Image curImage;
  /** Kludge for showStatus */
  static Label status;
  /** true if we are in drag */
  boolean inDrag = false;
  /** starting location of a drag */
  int startX = -1, startY = -1;
  /** current location of a drag */
  int curX = -1, curY = -1;
  // "main" method
  public static void main(String[] av) {
    JFrame f = new JFrame("Mouse Dragger");
    Container cp = f.getContentPane();
    if (av.length < 1) {
      System.err.println("Usage: MouseDrag imagefile");
      System.exit(1);
    }
    Image im = Toolkit.getDefaultToolkit().getImage(av[0]);
    // create a MouseDrag object
    MouseDrag j = new MouseDrag(im);
    cp.setLayout(new BorderLayout());
    cp.add(BorderLayout.NORTH, new Label(
        "Hello, and welcome to the world of Java"));
    cp.add(BorderLayout.CENTER, j);
    cp.add(BorderLayout.SOUTH, status = new Label());
    status.setSize(f.getSize().width, status.getSize().height);
    f.pack();
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  // "Constructor" - creates the object
  public MouseDrag(Image i) {
    super();
    curImage = i;
    setSize(300, 200);
    addMouseListener(this);
    addMouseMotionListener(this);
  }
  public void showStatus(String s) {
    status.setText(s);
  }
  // Five methods from MouseListener:
  /** Called when the mouse has been clicked on a component. */
  public void mouseClicked(MouseEvent e) {
  }
  /** Called when the mouse enters a component. */
  public void mouseEntered(MouseEvent e) {
  }
  /** Called when the mouse exits a component. */
  public void mouseExited(MouseEvent e) {
  }
  /** Called when the mouse has been pressed. */
  public void mousePressed(MouseEvent e) {
    Point p = e.getPoint();
    System.err.println("mousePressed at " + p);
    startX = p.x;
    startY = p.y;
    inDrag = true;
  }
  /** Called when the mouse has been released. */
  public void mouseReleased(MouseEvent e) {
    inDrag = false;
    System.err.println("SELECTION IS " + startX + "," + startY + " to "
        + curX + "," + curY);
  }
  // And two methods from MouseMotionListener:
  public void mouseDragged(MouseEvent e) {
    Point p = e.getPoint();
    // System.err.println("mouse drag to " + p);
    showStatus("mouse Dragged to " + p);
    curX = p.x;
    curY = p.y;
    if (inDrag) {
      repaint();
    }
  }
  public void paint(Graphics g) {
    int w = curX - startX, h = curY - startY;
    Dimension d = getSize();
    g.drawImage(curImage, 0, 0, d.width, d.height, this);
    if (startX < 0 || startY < 0)
      return;
    System.err.println("paint:drawRect @[" + startX + "," + startY
        + "] size " + w + "x" + h);
    g.setColor(Color.red);
    g.fillRect(startX, startY, w, h);
  }
  public void mouseMoved(MouseEvent e) {
    showStatus("mouse Moved to " + e.getPoint());
  }
}





Mouse Event Demo

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/*
 * MouseEventDemo.java is a 1.4 example that requires the following file:
 * BlankArea.java
 */
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class MouseEventDemo extends JPanel implements MouseListener {
  BlankArea blankArea;
  JTextArea textArea;
  final static String newline = "\n";
  public MouseEventDemo() {
    super(new GridBagLayout());
    GridBagLayout gridbag = (GridBagLayout) getLayout();
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1.0;
    c.weighty = 1.0;
    c.insets = new Insets(1, 1, 1, 1);
    blankArea = new BlankArea(new Color(0.98f, 0.97f, 0.85f));
    gridbag.setConstraints(blankArea, c);
    add(blankArea);
    c.insets = new Insets(0, 0, 0, 0);
    textArea = new JTextArea();
    textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane
        .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(200, 75));
    gridbag.setConstraints(scrollPane, c);
    add(scrollPane);
    //Register for mouse events on blankArea and the panel.
    blankArea.addMouseListener(this);
    addMouseListener(this);
    setPreferredSize(new Dimension(450, 450));
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  }
  public void mousePressed(MouseEvent e) {
    saySomething("Mouse pressed (# of clicks: " + e.getClickCount() + ")",
        e);
  }
  public void mouseReleased(MouseEvent e) {
    saySomething("Mouse released (# of clicks: " + e.getClickCount() + ")",
        e);
  }
  public void mouseEntered(MouseEvent e) {
    saySomething("Mouse entered", e);
  }
  public void mouseExited(MouseEvent e) {
    saySomething("Mouse exited", e);
  }
  public void mouseClicked(MouseEvent e) {
    saySomething("Mouse clicked (# of clicks: " + e.getClickCount() + ")",
        e);
  }
  void saySomething(String eventDescription, MouseEvent e) {
    textArea.append(eventDescription + " detected on "
        + e.getComponent().getClass().getName() + "." + newline);
    textArea.setCaretPosition(textArea.getDocument().getLength());
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("MouseEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new MouseEventDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}
class BlankArea extends JLabel {
  Dimension minSize = new Dimension(100, 100);
  public BlankArea(Color color) {
    setBackground(color);
    setOpaque(true);
    setBorder(BorderFactory.createLineBorder(Color.black));
  }
  public Dimension getMinimumSize() {
    return minSize;
  }
  public Dimension getPreferredSize() {
    return minSize;
  }
}





MouseMotion Event: mouse move and drag

  
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MouseMotionEventDemo extends JPanel implements MouseMotionListener {
  private int mX, mY;
  public MouseMotionEventDemo() {
    addMouseMotionListener(this);
    setVisible(true);
  }
  public void mouseMoved(MouseEvent me) {
    mX = (int) me.getPoint().getX();
    mY = (int) me.getPoint().getY();
    repaint();
  }
  public void mouseDragged(MouseEvent me) {
    mouseMoved(me);
  }
  public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.fillRect(mX, mY, 5, 5);
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new MouseMotionEventDemo());
    f.setSize(200, 200);
    f.show();
  }
}





Mouse Wheel Event Demo

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/*
 * MouseWheelEventDemo.java is a 1.4 example that requires no other files.
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class MouseWheelEventDemo extends JPanel implements MouseWheelListener {
  JTextArea textArea;
  JScrollPane scrollPane;
  final static String newline = "\n";
  public MouseWheelEventDemo() {
    super(new BorderLayout());
    textArea = new JTextArea();
    textArea.setEditable(false);
    scrollPane = new JScrollPane(textArea);
    scrollPane
        .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(400, 250));
    add(scrollPane, BorderLayout.CENTER);
    textArea.append("This text area displays information "
        + "about its mouse wheel events." + newline);
    //Register for mouse-wheel events on the text area.
    textArea.addMouseWheelListener(this);
    setPreferredSize(new Dimension(450, 350));
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  }
  public void mouseWheelMoved(MouseWheelEvent e) {
    String message;
    int notches = e.getWheelRotation();
    if (notches < 0) {
      message = "Mouse wheel moved UP " + -notches + " notch(es)"
          + newline;
    } else {
      message = "Mouse wheel moved DOWN " + notches + " notch(es)"
          + newline;
    }
    if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
      message += "    Scroll type: WHEEL_UNIT_SCROLL" + newline;
      message += "    Scroll amount: " + e.getScrollAmount()
          + " unit increments per notch" + newline;
      message += "    Units to scroll: " + e.getUnitsToScroll()
          + " unit increments" + newline;
      message += "    Vertical unit increment: "
          + scrollPane.getVerticalScrollBar().getUnitIncrement(1)
          + " pixels" + newline;
    } else { //scroll type == MouseWheelEvent.WHEEL_BLOCK_SCROLL
      message += "    Scroll type: WHEEL_BLOCK_SCROLL" + newline;
      message += "    Vertical block increment: "
          + scrollPane.getVerticalScrollBar().getBlockIncrement(1)
          + " pixels" + newline;
    }
    saySomething(message, e);
  }
  //Append to the text area and make sure the new text is visible.
  void saySomething(String eventDescription, MouseWheelEvent e) {
    textArea.append(e.getComponent().getClass().getName() + ": "
        + eventDescription);
    textArea.setCaretPosition(textArea.getDocument().getLength());
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("MouseWheelEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new MouseWheelEventDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}





Move and scale graphical objects with a mouse on the panel

  
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MouseMoveScale extends JPanel {
  private Rectangle2D.Float myRect = new Rectangle2D.Float(50, 50, 50, 50);
  MovingAdapter ma = new MovingAdapter();
  public MouseMoveScale() {
    addMouseMotionListener(ma);
    addMouseListener(ma);
    addMouseWheelListener(new ScaleHandler());
  }
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2d.setColor(new Color(0, 0, 200));
    g2d.fill(myRect);
  }
  class MovingAdapter extends MouseAdapter {
    private int x;
    private int y;
    public void mousePressed(MouseEvent e) {
      x = e.getX();
      y = e.getY();
    }
    public void mouseDragged(MouseEvent e) {
      int dx = e.getX() - x;
      int dy = e.getY() - y;
      if (myRect.getBounds2D().contains(x, y)) {
        myRect.x += dx;
        myRect.y += dy;
        repaint();
      }
      x += dx;
      y += dy;
    }
  }
  class ScaleHandler implements MouseWheelListener {
    public void mouseWheelMoved(MouseWheelEvent e) {
      int x = e.getX();
      int y = e.getY();
      if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
        if (myRect.getBounds2D().contains(x, y)) {
          float amount = e.getWheelRotation() * 5f;
          myRect.width += amount;
          myRect.height += amount;
          repaint();
        }
      }
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Moving and Scaling");
    MouseMoveScale m = new MouseMoveScale();
    m.setDoubleBuffered(true);
    frame.add(m);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}





Move Shape with mouse

  
import java.applet.Applet;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Label;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JApplet;
//Use double buffering to remove rectangle flickers and make it repaint faster.
public class ShapeMover extends JApplet {
  static protected Label label = new Label(
      "Drag rectangle around within the area");
  public void init() {
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(new MyCanvas());
    getContentPane().add("South", label);
  }
  public static void main(String s[]) {
    Frame f = new Frame("ShapeMover");
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    Applet applet = new ShapeMover();
    f.add("Center", applet);
    applet.init();
    f.pack();
    f.setSize(new Dimension(550, 250));
    f.show();
  }
}
class MyCanvas extends Canvas implements MouseListener, MouseMotionListener {
  Rectangle rect = new Rectangle(0, 0, 100, 50);
  Graphics2D g2;
  int preX, preY;
  boolean isFirstTime = true;
  Rectangle area;
  boolean pressOut = false;
  public MyCanvas() {
    setBackground(Color.white);
    addMouseMotionListener(this);
    addMouseListener(this);
  }
  public void mousePressed(MouseEvent e) {
    preX = rect.x - e.getX();
    preY = rect.y - e.getY();
    if (rect.contains(e.getX(), e.getY()))
      updateLocation(e);
    else {
      ShapeMover.label.setText("Drag it.");
      pressOut = true;
    }
  }
  public void mouseDragged(MouseEvent e) {
    if (!pressOut)
      updateLocation(e);
    else
      ShapeMover.label.setText("Drag it.");
  }
  public void mouseReleased(MouseEvent e) {
    if (rect.contains(e.getX(), e.getY()))
      updateLocation(e);
    else {
      ShapeMover.label.setText("Drag it.");
      pressOut = false;
    }
  }
  public void mouseMoved(MouseEvent e) {
  }
  public void mouseClicked(MouseEvent e) {
  }
  public void mouseExited(MouseEvent e) {
  }
  public void mouseEntered(MouseEvent e) {
  }
  public void updateLocation(MouseEvent e) {
    rect.setLocation(preX + e.getX(), preY + e.getY());
    if (checkRect()) {
      ShapeMover.label.setText(rect.getX() + ", " + rect.getY());
    } else {
      ShapeMover.label.setText("drag inside the area.");
    }
    repaint();
  }
  public void paint(Graphics g) {
    update(g);
  }
  public void update(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Dimension dim = getSize();
    int w = (int) dim.getWidth();
    int h = (int) dim.getHeight();
    g2.setStroke(new BasicStroke(8.0f));
    if (isFirstTime) {
      area = new Rectangle(dim);
      rect.setLocation(w / 2 - 50, h / 2 - 25);
      isFirstTime = false;
    }
    // Clears the rectangle that was previously drawn.
    g2.setPaint(Color.white);
    g2.fillRect(0, 0, w, h);
    g2.setColor(Color.red);
    g2.draw(rect);
    g2.setColor(Color.black);
    g2.fill(rect);
  }
  boolean checkRect() {
    if (area == null) {
      return false;
    }
    if (area.contains(rect.x, rect.y, 100, 50)) {
      return true;
    }
    int new_x = rect.x;
    int new_y = rect.y;
    if ((rect.x + 100) > area.getWidth()) {
      new_x = (int) area.getWidth() - 99;
    }
    if (rect.x < 0) {
      new_x = -1;
    }
    if ((rect.y + 50) > area.getHeight()) {
      new_y = (int) area.getHeight() - 49;
    }
    if (rect.y < 0) {
      new_y = -1;
    }
    rect.setLocation(new_x, new_y);
    return false;
  }
}





Swing Mouse Motion Event Demo

  
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
/*
 * SwingMouseMotionEventDemo.java is a 1.2/1.3/1.4 example that requires the
 * following file: BlankArea.java
 */
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class SwingMouseMotionEventDemo extends JPanel implements MouseMotionListener {
  BlankArea blankArea;
  JTextArea textArea;
  static final String newline = "\n";
  public SwingMouseMotionEventDemo() {
    super(new GridBagLayout());
    GridBagLayout gridbag = (GridBagLayout) getLayout();
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1.0;
    c.weighty = 1.0;
    c.insets = new Insets(1, 1, 1, 1);
    blankArea = new BlankArea(new Color(0.98f, 0.97f, 0.85f));
    gridbag.setConstraints(blankArea, c);
    add(blankArea);
    c.insets = new Insets(0, 0, 0, 0);
    textArea = new JTextArea();
    textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea,
        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setPreferredSize(new Dimension(200, 75));
    gridbag.setConstraints(scrollPane, c);
    add(scrollPane);
    //Register for mouse events on blankArea and panel.
    blankArea.addMouseMotionListener(this);
    addMouseMotionListener(this);
    setPreferredSize(new Dimension(450, 450));
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  }
  public void mouseMoved(MouseEvent e) {
    saySomething("Mouse moved", e);
  }
  public void mouseDragged(MouseEvent e) {
    saySomething("Mouse dragged", e);
  }
  void saySomething(String eventDescription, MouseEvent e) {
    textArea.append(eventDescription + " (" + e.getX() + "," + e.getY()
        + ")" + " detected on " + e.getComponent().getClass().getName()
        + newline);
    textArea.setCaretPosition(textArea.getDocument().getLength());
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("SwingMouseMotionEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new SwingMouseMotionEventDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}
class BlankArea extends JLabel {
  Dimension minSize = new Dimension(100, 100);
  public BlankArea(Color color) {
    setBackground(color);
    setOpaque(true);
    setBorder(BorderFactory.createLineBorder(Color.black));
  }
  public Dimension getMinimumSize() {
    return minSize;
  }
  public Dimension getPreferredSize() {
    return minSize;
  }
}