I am creating an applet that lets the user draw different shapes using the rubber band effect, letting the user see the shape while it is being drawn. What I want is for the program to draw shapes that stay on the screen. The problem is that the program draws a shape wherever the mouse is.
Take the program below, for example. Say the user clicks the applet at point (50,50) and drags the mouse to draw a rectangle with the bottom-right corner at (70,70). The program will draw several rectangles inside the final rectangle (i.e. rectangles with the bottom-right corner at (54,56), (63,61), etc.). I only want the final rectangle to be shown, but also while using the rubber band effect. If the user were to draw a second rectangle, the first one would remain on the screen while the user draws the second one.
How can I alter the code to make this work?
import java.awt.Graphics;
import java.awt.event.*;
public class Test extends java.applet.Applet implements MouseListener, MouseMotionListener {
int downX, downY, dragX, dragY;
public void init() {
downX = downY = dragX = dragY = 0;
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g) {
g.drawRect(downX,downY,dragX-downX,dragY-downY);
}
public void update(Graphics g) {
paint(g);
}
public void mouseClicked(MouseEvent e) {
downX = e.getX();
downY = e.getY();
}
public void mouseDragged(MouseEvent e) {
dragX = e.getX();
dragY = e.getY();
repaint();
}
public void /*Other MouseEvent methods*/ {}
}