/** * RubberLines.java * * Demonstrates events, listeners and rubberbanding. * @author Lewis and Loftus. Converted to JApplet by Scot Drysdale */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class RubberLines extends JApplet implements MouseListener, MouseMotionListener { private static final long serialVersionUID = 1L; private final int APPLET_WIDTH = 500; private final int APPLET_HEIGHT = 500; private Point point1 = null; private Point point2 = null; /** * Adds this class as a listener and does other initialization. */ public void init() { addMouseListener(this); addMouseMotionListener(this); setBackground(Color.black); setSize(APPLET_WIDTH, APPLET_HEIGHT); Container cp = getContentPane(); // Content pane holds components cp.add(new Canvas()); // The canvas is the only component setVisible(true); // Makes the applet (and its components) visible } /** * Captures the point where the mouse is pressed. * @param event the event that caused this callback */ public void mousePressed(MouseEvent event) { point1 = event.getPoint(); } /** * Gets the current position of the mouse as it is dragged and * draws the line to create the rubberband effect. * * @param event the event that caused this callback */ public void mouseDragged(MouseEvent event) { point2 = event.getPoint(); repaint(); } //----------------------------------------------------------------- // Provide empty definitions for unused event methods. //----------------------------------------------------------------- public void mouseClicked(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} public void mouseMoved(MouseEvent event) {} /** * Serves as the drawing canvas for graphics. */ private class Canvas extends JPanel { private static final long serialVersionUID = 1L; /** * Paints this component. * @param page the Graphics object that we draw on. */ public void paintComponent(Graphics page) { super.paintComponent(page); page.setColor(Color.red); if (point1 != null && point2 != null) page.drawLine(point1.x, point1.y, point2.x, point2.y); } } }