gpt4 book ai didi

java - 如何在 Java 中移动矩形?

转载 作者:行者123 更新时间:2023-12-04 16:45:29 25 4
gpt4 key购买 nike

我正在尝试移动一个矩形,但我不确定该怎么做,我知道它与“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) {}
}

最佳答案

新答案如果您希望能够单击并拖动矩形,您基本上只需更新矩形的 x 和 y,并让鼠标监听器将这些值更改为单击时鼠标的当前位置。

旧答案

Your question is a little confusing. You mention using mouseClicked(MouseEvent e) yet that hasing nothing to do with actually moving the rectangle that deals with a event where the mouse is clicked.

If you just want to move your rectangle you could have a variable and add to the x or y. For Example:

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

Then in your public void run you could do:

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

Or for if the mouse was clicked basically you'd be using the mouse event and when it's clicked you would just set that x and y to the mouse's position.

关于java - 如何在 Java 中移动矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8204120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com