如何在Java中移动矩形?

时间:2011-11-20 19:38:14

标签: java applet awt

我正在尝试移动一个矩形,但我不知道该怎么做,我知道它与'mouseClicked(MouseEvent e)`有关,但不知道如何使用它。这是我到目前为止的代码:

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) {}
 }

5 个答案:

答案 0 :(得分:5)

新答案 如果你想能够点击并拖动矩形,你只需要更新矩形的x和y,并让鼠标监听器在点击时将这些值更改为鼠标当前位置。

旧答案

  

你的问题有点令人困惑。你提到使用   mouseClicked(MouseEvent e)但与此毫无关系   实际上移动处理鼠标事件的矩形   点击。

     

如果您只想移动矩形,可以使用变量和   添加到x或y。例如:

int x = 100;
int y = 100;    
g.fillRect(x,y,100,100);
     

然后在你的公共无效运行中你可以做到:

      try
      {
        Thread.sleep(100);
      }catch(Exception e)
      {
      }
      x = x + 2;
      y = y +2;
      repaint();
     

或者,如果点击鼠标基本上你正在使用鼠标   事件,当它被点击时,你只需将x和y设置为   老鼠的位置。

答案 1 :(得分:1)

您需要将鼠标侦听器添加到要侦听的对象。查看http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html它将帮助您开始设置鼠标监听器 你还在哪里卡住?让听众工作?或者让矩形移动?

答案 2 :(得分:1)

如果您希望能够“绘制”矩形,这个snipet可以很好地工作。

public int XVal = 0 , YVal = 0;

public void paint(Graphics g) {

    g.fillRect(XVal, YVal, 20, 20);

    addMouseMotionListener(
            new MouseMotionAdapter() {

                public void mouseDragged(MouseEvent e) {

                    XVal = e.getX();
                    YVal = e.getY();
                    repaint();
                }
            });
} 

答案 3 :(得分:1)

为了让它顺序移动,您需要获得始终的相对位置 currentPosition - LastPosition。您可以使用mouseMove存储当前位置。

public void mouseMoved(MouseEvent e)
{
  _relativePosition.x = e.getX() - _currentPosition.x;
  _relativePosition.y = e.getX() - _currentPosition.y;
  _currentPosition.x = e.getX();
  _currentPosition.y = e.getY();
}

答案 4 :(得分:1)

你只需要在tick方法()中增加x或y变量;