Установка положения дуги в Java с помощью мыши

Я пишу 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

Как я это сделаю? (Извините за мои плохие навыки рисования!)

1 ответ

Решение

Так что на основе информации из Java 2d вращения в направлении точки мыши

Нам нужны две вещи. Нам нужна точка привязки (которая будет центральной точкой дуги) и целевая точка, которая будет точкой мыши.

Используя 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 градусов.

Другие вопросы по тегам