Java Reference
In-Depth Information
ScriblePane1 example (and a sample scribble) running within the ShowComponent
program developed at the start of this chapter.
Figure 10•10. A scribble in ScribblePane1
Note that the ScribblePane1 class is both the source of mouse events (they are
generated by the java.awt.Component superclass) and the event listener. This can
be seen most clearly in the constructor method where the component passes itself
to its own addMouseListener() and addMouseMotionListener() methods. The
mouseDragged() method is the key to scribbling: it uses the drawLine() method of
the Graphics object to draw a line from the previous mouse position to the current
mouse position.
Example 10•11: ScribblePane1.java
package com.davidflanagan.examples.gui;
import javax.swing.*;
// For JPanel component
import java.awt.*;
// For Graphics object
import java.awt.event.*;
// For Event and Listener objects
/**
* A simple JPanel subclass that uses event listeners to allow the user
* to scribble with the mouse. Note that scribbles are not saved or redrawn.
**/
public class ScribblePane1 extends JPanel
implements MouseListener, MouseMotionListener {
protected int last_x, last_y; // Previous mouse coordinates
public ScribblePane1() {
// This component registers itself as an event listener for
// mouse events and mouse motion events.
this.addMouseListener(this);
this.addMouseMotionListener(this);
// Give the component a preferred size
setPreferredSize(new Dimension(450,200));
}
Search WWH ::




Custom Search