0

I am trying to draw a line where the start point is when the mouse is pressed and while it is being dragged it continues to draw the line until the mouse is released. I'm trying to make something like MS Paint.

What the code does though it starts at the centre of the program and draws the line in both directions.

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();
}
Farfar
  • 1
  • 2
  • 1
    Possible duplicate of [How to draw a continuous line with mouse on JavaFX canvas?](https://stackoverflow.com/questions/43429251/how-to-draw-a-continuous-line-with-mouse-on-javafx-canvas) – faris Oct 08 '18 at 05:18
  • create new line instead of changing existing one – Sergey Grinev Oct 08 '18 at 05:35
  • Just replace `BorderPane` with `Pane`. If you want to make something like MS Paint, then better use `Canvas`. Here is tutorial - https://docs.oracle.com/javafx/2/canvas/jfxpub-canvas.htm – gearquicker Oct 08 '18 at 16:17
  • Ok that does help but now every time I drag the mouse it draws lines. I just need one line and its end points moves as I drag – Farfar Oct 09 '18 at 03:35

0 Answers0