我正在写一个2D程序。在paintComponent
我创建了一个弧。
public class Board extends Panel{
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D graphics2d = (Graphics2D)g;
int x = MouseInfo.getPointerInfo().getLocation().x;//set mouses current position
int y = MouseInfo.getPointerInfo().getLocation().y;
graphics2d.setStroke(wideStroke);
graphics2d.draw(new Arc2D.Double(200, 200, 100, 100, ?, 180, Arc2D.OPEN));
}
}
在我的主要内容中,我使用Thread
来更新图表。 ?
的位置是起始角度。每当我改变这个时,弧就会像一个车轮一样移动一圈。是否有可能让弧线运动跟随鼠标?例如? = 270
我将如何做到这一点? (对不起我糟糕的油漆技巧!)
答案 0 :(得分:1)
所以基于Java 2d rotation in direction mouse point
的信息我们需要两件事。我们需要锚点(它将是弧的中心点)和目标点,这将是鼠标点。
使用MouseMotionListener
,可以监控组件中的鼠标移动
// Reference to the last known position of the mouse...
private Point mousePoint;
//....
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
mousePoint = e.getPoint();
repaint();
}
});
接下来我们需要计算这两点之间的角度......
if (mousePoint != null) {
// This represents the anchor point, in this case,
// the centre of the component...
int x = width / 2;
int y = height / 2;
// This is the difference between the anchor point
// and the mouse. Its important that this is done
// within the local coordinate space of the component,
// this means either the MouseMotionListener needs to
// be registered to the component itself (preferably)
// or the mouse coordinates need to be converted into
// local coordinate space
int deltaX = mousePoint.x - x;
int deltaY = mousePoint.y - y;
// Calculate the angle...
// This is our "0" or start angle..
rotation = -Math.atan2(deltaX, deltaY);
rotation = Math.toDegrees(rotation) + 180;
}
从这里开始,您需要减去90度,这将使您的弧开始角度,然后使用180度的范围。