gpt4 book ai didi

java - 使用鼠标在 Java 中设置圆弧位置

转载 作者:行者123 更新时间:2023-12-01 13:03:11 25 4
gpt4 key购买 nike

我正在编写一个 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));

}
}

在我的 main 中,我使用 Thread 来更新图表。 ? 的位置是起始角度。每次我更改此设置时,圆弧都会像半个车轮一样绕圈移动。是否可以让弧线跟随鼠标移动?例如? = 270

enter image description here

我将如何做到这一点? (抱歉我的画技不好!)

最佳答案

所以根据Java 2d rotation in direction mouse point的信息

我们需要两件事。我们需要 anchor (即圆弧的中心点)和目标点(即鼠标点)。

使用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 度的范围。

关于java - 使用鼠标在 Java 中设置圆弧位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23398744/

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