684 Graphical User Interface Components: Part 1 (Free web host) Chapter
684 Graphical User Interface Components: Part 1 Chapter 12 The Painter application of Fig. 12.19 uses the mouseDragged event handler to create a simple drawing program. The user can draw pictures with the mouse by dragging the mouse on the background of the window. This example does not use method mouse- Moved, so our MouseMotionListener is defined as a subclass of Mouse- MotionAdapter. This class already defines both mouseMovedand mouseDragged, so we can simply override mouseDraggedto provide the drawing functionality. 1 // Fig. 12.19: Painter.java 2 // Using class MouseMotionAdapter. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class Painter extends JFrame { 12 private int xValue = -10, yValue = -10; 13 14 // set up GUI and register mouse event handler 15 public Painter() 16 { 17 super( “A simple paint program” ); 18 19 // create a label and place it in SOUTH of BorderLayout 20 getContentPane().add( 21 new Label( “Drag the mouse to draw” ), 22 BorderLayout.SOUTH ); 23 24 addMouseMotionListener( 25 26 // anonymous inner class 27 new MouseMotionAdapter() { 28 29 // store drag coordinates and repaint 30 public void mouseDragged( MouseEvent event ) 31 { 32 xValue = event.getX(); 33 yValue = event.getY(); 34 repaint(); 35 } 36 37 } // end anonymous inner class 38 39 ); // end call to addMouseMotionListener 40 41 setSize( 300, 150 ); 42 setVisible( true ); 43 } 44 Fig. 12.19 Fig. 12.19 Program that demonstrates adapter classes (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01