Question: JAVA FX When the user stops drawing (releases the mouse button), the canvas should draw a straight line from the endpoint of the drawn shape

JAVA FX

When the user stops drawing (releases the mouse button), the canvas should draw a straight line from the endpoint of the drawn shape to the starting point. Also, you should implement the "eraser" function: the mouse's secondary button (the right button for right-handed people) should paint the canvas white, thus "erasing" the content under the cursor. (using strokeLine() and clearRect() in GraphicsContext interface

Based on the following code:

import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.BorderPane; import javafx.scene.paint.Color; import javafx.stage.Stage;

public class MainApp1 extends Application {

@Override public void start(Stage stage) throws Exception { Canvas drawCanvas = new Canvas(1000,800); BorderPane root = new BorderPane(); root.setCenter(drawCanvas);

GraphicsContext gc = drawCanvas.getGraphicsContext2D();

//add mouse moved event drawCanvas.setOnMouseDragged( e -> { gc.setFill(Color.WHITE); gc.fillRect(0, 0, 1000, 800); gc.setLineWidth(5); gc.lineTo(e.getX(), e.getY()); gc.stroke(); });

drawCanvas.setOnMouseMoved( e -> { gc.moveTo(e.getX(), e.getY()); });

stage.setScene(new Scene(root)); stage.show();

}

public static void main(String[] args){ launch(args); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!