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

enter image description here

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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top