In: Computer Science
Write a JavaFX application that draws a circle using a rubberbanding technique. The circle size is determined by a mouse drag. Use the initial mouse press location as the fixed center point of the circle. Compute the distance between the current location of the mouse pointer and the center point to determine the current radius of the circle.
Hi. I have answered similar questions before. Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
// DrawCircles.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
public class DrawCircles extends Application {
private Scene scene;
private Circle c;
//a flag denoting if a circle is being drawn or not
private boolean isDrawing;
Pane pane;
@Override
public void start(Stage primaryStage) {
//initializing circle to null
c = null;
//setting isDrawing to false
isDrawing = false;
//initializing pane
pane = new Pane();
//initializing scene.
scene = new Scene(pane, 500, 500, Color.WHITE);
//adding mouse listeners to the scene
scene.setOnMousePressed(this::processMousePress);
scene.setOnMouseDragged(this::processMouseDrag);
scene.setOnMouseReleased(this::processMouseRelease);
//setting up and displaying the scene
primaryStage.setTitle("Rubberband Circle");
primaryStage.setScene(scene);
primaryStage.show();
}
//mouse press handler method
public void processMousePress(MouseEvent e) {
//only if the circle is not being drawn, setting isDrawing to true
if (!isDrawing) {
isDrawing = true;
//initializing circle
c = new Circle(e.getX(), e.getY(), 5);
//using no fill color
c.setFill(null);
//using black stroke color
c.setStroke(Color.BLACK);
//clearing current contents of pane and adding c.
//if you want to keep the current circle when drawing another, remove below single line
pane.getChildren().clear();
pane.getChildren().add(c);
}
}
//mouse drag handler method
public void processMouseDrag(MouseEvent e) {
//using distance formula, finding the distance from current mouse point to circle's center
double radius = Math.sqrt(Math.pow((e.getX() - c.getCenterX()), 2) + Math.pow((e.getY() - c.getCenterY()), 2));
//setting above value as circle's radius
c.setRadius(radius);
}
//handler method for mouse release operation
public void processMouseRelease(MouseEvent e) {
//simply setting isDrawing to false to enable drawing of next circle on next mouse press
isDrawing = false;
}
public static void main(String[] args) {
launch(args);
}
}
/*OUTPUT*/