JavaFX用鼠标画线

时间:2018-10-08 03:24:01

标签: java javafx

我试图画一条线,该点的起点是按下鼠标时的位置,在拖动时它会继续画线,直到释放鼠标为止。我正在尝试制作类似MS Paint的东西。

尽管代码从程序的中心开始并在两个方向上画线,但代码的作用。

public void start(Stage primaryStage) {
    BorderPane root = new BorderPane();

    Line l1 = new Line();
    root.addEventHandler(MouseEvent.ANY, event ->{
        if(event.getEventType() == MouseEvent.MOUSE_PRESSED) {
            firstX = event.getX();
            firstY = event.getY();

            l1.setStartX(firstX);
            l1.setStartY(firstY);

        } if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
            double deltaX = event.getX();
            double deltaY = event.getY();

            l1.setEndX(deltaX);
            l1.setEndY(deltaY);
        } if (event.getEventType() == MouseEvent.MOUSE_RELEASED) {
            endX = event.getX();
            endY = event.getY();

            l1.setEndX(endX);
            l1.setEndY(endY);
        }
    });

    root.setCenter(l1);

    Scene scene = new Scene(root, 300, 300);
    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

0 个答案:

没有答案