/* * ============================================================== * DemoMouseMotion.java : Demonstrates mouse motion events. * * Adapted from : Pantham S., Pure JFC Swing, 1999. * Modified by Mark Austin March, 2001 * ============================================================== */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DemoMouseMotion extends JApplet { int x, y; int flag; public void init() { // 1. Create an object of the custom listener and register it with // the applet. CustomListener ct = new CustomListener(this); this.addMouseMotionListener(ct); } // 2. The update() method to repair the applet's background. // This can reduce the performance and lead to flickering. // The workaround is to use a JPanel attached to the applet. public void update(Graphics g) { g.setColor( this.getBackground() ); g.fillRect(0, 0, getWidth(), getHeight()); paint(g); } // 3. The paint() method to display the mode of mouse motion // and its location, depending on the flag value. public void paint(Graphics g) { g.setColor(Color.blue); g.drawString("Drag/Move the Mouse ...", 5, 20); g.setColor(Color.red); if(flag == 1) { g.drawString("Don't Move! Drag the Mouse!", 5, 85); g.drawString("Cursor Coordinates: " + x + ", " + y, 5, 95); } else if(flag == 2) { g.drawString("Don't Drag! Move the Mouse!", 5, 85); g.drawString("Cursor Coordinates: " + x + ", " + y, 5, 95); } } } // 4. The mouse motion listener. class CustomListener implements MouseMotionListener { DemoMouseMotion dmm; public CustomListener( DemoMouseMotion dmm ) { this.dmm = dmm; } // Executed when the mouse is moved. public void mouseMoved(MouseEvent me) { // Set the flag value dmm.flag = 1; // Get the coordinates of the mouse pointer. dmm.x = me.getX(); dmm.y = me.getY(); // Repaint the applet. dmm.repaint(); } // Executed when the mouse is dragged. public void mouseDragged(MouseEvent me) { // Set the flag value dmm.flag = 2; // Get the coordinates of the mouse pointer. dmm.x = me.getX(); dmm.y = me.getY(); // Repaint the applet. dmm.repaint(); } }