I am trying to move a rectangle but I am not sure how to do it, I know it something to do with ‘mouseClicked(MouseEvent e)` but don’t know how to use it. This is the code I have so far:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MovRect extends Applet implements MouseMotionListener, MouseListener {
Color color = Color.green;
int x=30,y=30,w=150,l=150;
String MouseMotion ="";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(color);
g.drawRect(x, y, w, l);
}
public void mouseClicked(MouseEvent e)
{
String clickDesc;
if (e.getClickCount() == 2)
clickDesc = "double";
else
clickDesc = "single";
System.out.println("Mouse was " + clickDesc + "-clicked at location (" +
e.getX() + ", " + e.getY() + ")");
int mouseX = e.getX();
int mouseY = e.getY();
if( mouseX >= x && mouseX <= x+w && mouseY >= y && mouseY <= y+l )
{
}
else
{
}
this.repaint();
}
public void mouseDragged(MouseEvent e)
{
System.out.println("mouse is being dragged at location (" + e.getX() + ", " + e.getY() + ")");
MouseMotion ="mouseDragged";
repaint();
}
public void mouseMoved(MouseEvent e)
{
System.out.println("mouse is being moved at location (" + e.getX() + ", " + e.getY() + ")");
MouseMotion ="mouseMoved";
repaint();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
New answer
If you want to be able to click and drag the rectangle you just basically update the x and y of the rectangle and have a mouse listener change those values to the mouses current position on click.
Old Answer