在JavaFX中拖动鼠标时,圆圈不可见

时间:2016-11-16 10:32:56

标签: java javafx javafx-2 javafx-8

我在JavaFX中创建了一个小型绘图程序,并且有一个圆形创建工具。目前,我可以正确地绘制圆圈,但与我的其他工具不同,我不能看到圆圈正在被创建(即我正在拖动我的鼠标)。只有当我释放鼠标时才能看到圆圈(用正确的尺寸绘制)。我试图在拖动的时候添加strokeOval()方法,但它创建了一个奇怪的" teardrop"喜欢圈子。我尝试了一切 - 有人可以帮忙吗?

这是我的代码:

public CircleController(Canvas canvas, Scene mainScene, BorderPane borderPane) {

    this.borderPane = borderPane;
    this.mainScene = mainScene;
    this.graphicsContext = canvas.getGraphicsContext2D();

    circle = new Circle();
    circle.setStrokeWidth(1.0);
    circle.setFill(Color.WHITE);
    circle.setStroke(Color.BLACK);

    mousePressed = event -> {
        startingPosX = event.getX();
        startingPosY = event.getY();
        borderPane.getChildren().add(circle);

    };

    mouseReleased = event -> {
        borderPane.getChildren().remove(circle);
        double width = Math.abs(event.getX() - startingPosX);
        double height = Math.abs(event.getY() - startingPosY);
        graphicsContext.strokeOval(startingPosX, startingPosY, width, height);
        graphicsContext.setStroke(Color.BLACK);
        removeListeners();
    };

    mouseDragged = event -> {
        circle.setCenterX(event.getX() - startingPosX);
        circle.setCenterY(event.getY() - startingPosY);

    };
}

上面的代码正确地创建了圆圈,但在我释放鼠标之前无法看到。我将上面的EventHandlers应用到我的场景中:

@Override
public void handle(ActionEvent event) {
    mainScene.setOnMousePressed(mousePressed);
    mainScene.setOnMouseDragged(mouseDragged);
    mainScene.setOnMouseReleased(mouseReleased);
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您正在绘制椭圆而不是Circle类无法正确处理此问题。您需要Ellipse。此外请注意,从手势开始向上/向左拖动会导致椭圆的奇怪行为,因为它始终在坐标系的第一个象限中绘制,并且在拖动手势的开始处具有原点。

以下代码应允许在每个象限中绘制椭圆,并使用Ellipse作为"预览":

// TODO: replace circle field with ellipse field of type Ellipse
ellipse = new Ellipse();
ellipse.setStrokeWidth(1.0);
ellipse.setFill(Color.TRANSPARENT);
ellipse.setStroke(Color.BLACK);

mousePressed = event -> {
    startingPosX = event.getX();
    startingPosY = event.getY();
    ellipse.setCenterX(startingPosX);
    ellipse.setCenterY(startingPosY);
    ellipse.setRadiusX(0);
    ellipse.setRadiusY(0);
    borderPane.getChildren().add(ellipse);
};

mouseReleased = event -> {
    borderPane.getChildren().remove(ellipse);
    double width = Math.abs(event.getX() - startingPosX);
    double height = Math.abs(event.getY() - startingPosY);
    graphicsContext.setStroke(Color.BLACK);
    graphicsContext.strokeOval(Math.min(startingPosX, event.getX()), Math.min(startingPosY, event.getY()), width, height);
    removeListeners();
};

mouseDragged = event -> {
    ellipse.setCenterX((event.getX() + startingPosX) / 2);
    ellipse.setCenterY((event.getY() + startingPosY) / 2);
    ellipse.setRadiusX(Math.abs((event.getX() - startingPosX) / 2));
    ellipse.setRadiusY(Math.abs((event.getY() - startingPosY) / 2));
};