【问题标题】:Setting arc position in Java using Mouse使用鼠标在 Java 中设置圆弧位置
【发布时间】:2014-04-30 21:59:22
【问题描述】:

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

我将如何做到这一点? (对不起我的绘画技巧不好!)

【问题讨论】:

  • 类似this FYI-MouseInfo 我们不是一个好的选择,MouseMotionListener 可能是一个更好的选择
  • @MadProgrammer。将其更改为 MouseMotionListener 不是问题。

标签: java graphics mouse paintcomponent pane


【解决方案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 度的范围。

【讨论】:

  • 我了解您在这段代码中向我展示的内容。我唯一的问题是如何让拱门用鼠标旋转?
  • MouseMotionListener 保持上一次鼠标位置,调用 repaint,计算角度并绘制圆弧。有关可运行示例,请参阅链接示例
  • 谢谢你,这应该会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多