Let's look at the code, which can be found in DrawBox.java:
Line 1 and 2 specify what classes to import. These are the, by now familiar:
import java.awt.*; import java.applet.Applet;Line 4 specifies the DrawBox class as extending the Applet class. It starts by declaring 4 integers and one boolean:
public class DrawBox extends Applet { int currentX, currentY, startX, startY; boolean dragMode = false;The 4 integers will be used to remember the coordinates of the mouse, so that a rectangle can be drawn if necessary. The boolean dragMode specifies whether or not the mouse is being dragged. A mouse drag means that the mouse is being moved while being pressed at the same time.
public void paint(Graphics g) { int beginX, beginY, width, height; if (dragMode == true) { beginX = Math.min(startX, currentX); beginY = Math.min(startY, currentY); width = Math.abs(currentX - startX); height = Math.abs(currentY - startY); g.drawRect(beginX, beginY, width, height); } else { g.drawString("Draw a box by dragging the mouse", 10, 25); } }The rectangle is drawn only if we are actually dragging the mouse. If we are not dragging the mouse, then the program prints out the string "Draw a box by dragging the mouse". If we are dragging the mouse, however, then we need to draw a rectangle. the drawRect method takes 4 arguments: an (x,y) coordinate of where to begin, and a width and a height. To get the begining point, we need to set the begin point of the rectangle to be the minimum of the start and current points. This is because there are four ways a user can drag a rectangle (topleft-to-bottomright, topright-to-bottomleft, bottomleft-to-topright, bottomright-to-topleft), and only one way to draw it. Then we calculate the width and height as being the absolute value of the difference of the current and the starting point's x and y values respectively. For calculating the minimum and absolute value, we used methods from the java.lang.Math class.
public boolean mouseDown(Event event, int x, int y) { dragMode = true; startX = x; startY = y; return true; }When the user releases the mouse button, a mouseUp gets issued. By overwriting the mouseUp we can take the necessary actions. In this case. we only need to set the dragMode variable back to false, so that the paint method prints the text string "Draw a box by dragging the mouse" again:
public boolean mouseUp(Event event, int x, int y) { dragMode = false; return true; }When the user drags the mouse button, a mouseDrag gets issued. Now, we set the currentX and currentY variables to the current mouse position (if we are in drag mode), and repaint the applet window (which causes the rectangle to be displayed):
public boolean mouseDrag(Event event, int x, int y) { if (dragMode == true) { currentX = x; currentY = y; repaint(); } return true; }