title: how to draw a straight line in javafx that updates itself when the user moves the mouse?
body: <p>So, I know how to do free hand lines but I want a straight line so when a user clicks a point to the point where the user releases the mouse and when the user drags the mouse the end point should move with the mouse i.e similar to drawing straight lines in the paint app.</p>
  
  <p>Presently working with this code:</p>
  
  <pre><code>public class JavaFX_DrawOnCanvas extends Application {
  
      @Override
      public void start(Stage primaryStage) {
  
          Canvas canvas = new Canvas(400, 400);
          final GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
          initDraw(graphicsContext);
  
          canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, 
                  new EventHandler&lt;MouseEvent&gt;(){
  
              @Override
              public void handle(MouseEvent event) {
                  graphicsContext.beginPath();
                  graphicsContext.moveTo(event.getX(), event.getY());
                  graphicsContext.stroke();
              }
          });
  
          canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, 
                  new EventHandler&lt;MouseEvent&gt;(){
  
              @Override
              public void handle(MouseEvent event) {
                  graphicsContext.lineTo(event.getX(), event.getY());
                  graphicsContext.stroke();
              }
          });
  
          canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, 
                  new EventHandler&lt;MouseEvent&gt;(){
  
              @Override
              public void handle(MouseEvent event) {
  
              }
          });
  
          StackPane root = new StackPane();
          root.getChildren().add(canvas);
          Scene scene = new Scene(root, 400, 400);
          primaryStage.setTitle("java-buddy.blogspot.com");
          primaryStage.setScene(scene);
          primaryStage.show();
      }
  
      public static void main(String[] args) {
          launch(args);
      }
  
      private void initDraw(GraphicsContext gc){
          double canvasWidth = gc.getCanvas().getWidth();
          double canvasHeight = gc.getCanvas().getHeight();
  
          gc.setFill(Color.LIGHTGRAY);
          gc.setStroke(Color.BLACK);
          gc.setLineWidth(5);
  
          gc.fill();
          gc.strokeRect(
                  0,              //x of the upper left corner
                  0,              //y of the upper left corner
                  canvasWidth,    //width of the rectangle
                  canvasHeight);  //height of the rectangle
  
          gc.setFill(Color.RED);
          gc.setStroke(Color.BLUE);
          gc.setLineWidth(1);
  
      }
  
  }
  </code></pre>
  
  <p>How to modify the mouse drag event to draw straight lines and not free hand? </p>