Hello,
Please some one help with this,
actually what i m tryin to do is, when i mouse click n drag the mouse n release it , i want a rectangle to be drawn.
and when i click on another location then also i want a rectangle to be drawn and the previusly drawn rectangle should also be vissible.
I am able to draw the rectangle but whe i draw a new rectangle the old rectangle vanishes.
i should be able to draw any number of rectangles, and all the rectangle
should be vissible.
can any one plz help me with this.
Plz help
Regards
Sanam
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<
applet code = "Test.class" width = 1020 height = 600>
</applet>
*/
public class
Test extends Applet implements MouseListener
{
private Color color = Color.black;
int x1, y1, x2, y2 = 0;
int width, height = 0;
int startX, startY = 0;
boolean drawObject = false;
boolean moveObject = false;
Rectangle myRectangle = new Rectangle(startX,startY,width,height);
public void init()
{
setBackground(Color.gray);
addMouseListener(this);
int i = 5;
}
public void paint(Graphics g)
{
//recover Graphics2D
Graphics2D g2 = (Graphics2D)g;
g2.setColor(color);
if(drawObject)
{
//create Rectangle Object
myRectangle = new Rectangle(startX,startY,width,height);
}
else if (moveObject)
{
myRectangle.setLocation(x2,y2);
}
g2.draw(myRectangle);
}
/////////////////////////////////////////////////////
//--> Start of section dealing with Mouse Events
/////////////////////////////////////////////////////
public void mouseClicked(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mousePressed(MouseEvent e)
{
x1 = e.getX();
y1 = e.getY();
//Check to see if mouse is pressed in the current rectangle.
if(myRectangle.contains(x1,y1))
{
//move the object instead of moving it
drawObject = false;
moveObject = true;
}
else
{
//draw the object, don't move
drawObject = true;
moveObject = false;
}
}
public void mouseReleased(MouseEvent e)
{
//get the positions of where the mouse was released
x2 = e.getX();
y2 = e.getY();
if (x1 != x2 && y1 != y2)
{
//maths to work out where to draw the object
if(x1 < x2 && y1 < y2)
{//1
startX = x1;
startY = y1;
height = y2 - y1;
width = x2 - x1;
}
else if (x1 > x2 && y1 > y2)
{//2
startX = x2;
startY = y2;
height = y1 - y2;
width = x1 - x2;
}
else if (x1 > x2 && y1 < y2)
{//3
startX = x2;
startY = y1;
height = y2 - y1;
width = x1 - x2;
}
else if (x1 < x2 && y1 > y2)
{//4
startX = x1;
startY = y2;
height = y1 - y2;
width = x2 - x1;
}
}
repaint();
}
}