can you guys help me how can I remove all those drawn rectangles if user click the mouse in the applet field?
I am supposed to write a program that displays a rectangle and color it with green when user drag the mouse. But if user click the mouse anywhere in the field then that rectangle should disappear.
I have got all working except that mouse clicked part.
Here is my code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawRect extends JApplet
{
private int pointCounter =0;
private Point coordinate1[] = new Point[20];
private Point coordinate2[] = new Point[20];
private Point beg = new Point();
private Point last = new Point();
Rectangle rectn = new Rectangle();
private boolean flag;
public DrawRect()
{
addMouseMotionListener( new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
last = e.getPoint();
rectn.setFrameFromDiagonal(beg, last);
repaint();
}
});
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
beg = e.getPoint();
}
public void mouseReleased(MouseEvent e)
{
coordinate1[pointCounter] = beg;
coordinate2[pointCounter] = e.getPoint();
pointCounter++;
rectn.setFrameFromDiagonal(beg, beg);
repaint();
}
public void mouseClicked(MouseEvent e)
{
if(flag==false)
{
repaint();
}
}
});
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
g2.draw(rectn);
g2.setPaint(Color.yellow);
Rectangle rectn2 = new Rectangle();
for (int i =0; i < pointCounter; i++)
{
rectn2.setFrameFromDiagonal(coordinate1[i], coordinate2[i]);
g2.fill(rectn2);
}
}
}