Setting arc position in Java using Mouse

旧街凉风 提交于 2019-12-25 02:46:44

问题


I am writing a 2D program. On my paintComponent I created an arc.

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));

    }
}

In my main I am using a Thread to update the graph. The position of the ? is the starting angle. Every time I change this the arc will move in a circle like half a car wheel. Is it possible to get the arc movement to follow the mouse? e.g. ? = 270

How will I do this? (Sorry for my bad paint skills!)


回答1:


So based on the information from Java 2d rotation in direction mouse point

We need two things. We need the anchor point (which would be the centre point of the arc) and the target point, which would be the mouse point.

Using a MouseMotionListener, its possible to monitor the mouse movements within the component

// 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();                    
    }                
});

Next we need to calculate the angle between these two points...

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;
}

From here, you would need to subtract 90 degrees, which would give your arcs start angle and then use an extent of 180 degrees.



来源:https://stackoverflow.com/questions/23398744/setting-arc-position-in-java-using-mouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!