Run it. Drag the mouse in any direction in the applet window .. and see what happens ... I hope you get some idea from it ....
package raj_java;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class DesktopDemo extends Applet implements MouseListener, MouseMotionListener {
int x1, y1, x2, y2;
Image img;
public void init() {
setSize(1200, 700);
setVisible(true);
img = getImage(getCodeBase(), "Nature.jpg");
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseClicked(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
Graphics g = getGraphics();
g.drawImage(img, 0, 0, 1200, 700, this);
}
public void mouseMoved(MouseEvent me) {
}
public void mousePressed(MouseEvent me) {
x1 = me.getX();
y1 = me.getY();
}
public void mouseDragged(MouseEvent me) {
x2 = me.getX();
y2 = me.getY();
repaint();
}
public void paint(Graphics g) {
g.drawImage(img, 0, 0, 1200, 700, this);
g.setColor(new Color(10, 99, 126));
g.drawLine(x1, y1, x2, y1);
g.drawLine(x2, y1, x2, y2);
g.drawLine(x2, y2, x1, y2);
g.drawLine(x1, y2, x1, y1);
g.setColor(new Color(193, 214, 220, 70));
int width = Math.abs(x2 - x1);
int height = Math.abs(y2 - y1);
if(x2 < x1) {
g.fillRect(x2, y1, width, height);
}else if(y2 < y1) {
g.fillRect(x1, y2, width, height);
}else {
g.fillRect(x1, y1, width, height);
}
}
}