JavaFX Pane add random circle on mouse event

Description

JavaFX Pane add random circle on mouse event

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {
   @Override/* w  w  w . j  a  v  a2s . c o  m*/
   public void start(Stage primaryStage) {
      Pane pane = new Pane();
      double width = 200; // pane width
      double height = 200; // pane height

      // Create a circle
      Circle circle = new Circle(10);
      setRandomProperties(circle, width, height);
      pane.getChildren().add(circle);

      // Create and register the handle
      circle.setOnMouseClicked(e -> {
         pane.getChildren().clear();
         setRandomProperties(circle, width, height);
         pane.getChildren().add(circle);
      });

      // Create a scene and place it in the stage
      Scene scene = new Scene(pane, width, height);
      primaryStage.setTitle("java2s.com");
      primaryStage.setScene(scene);
      primaryStage.show();
   }

   private void setRandomProperties(Circle c, double width, double height) {
      c.setFill(Color.color(Math.random(), Math.random(), Math.random()));
      c.setCenterX(c.getRadius() + Math.random() * 
         (width - c.getRadius() * 2));
      c.setCenterY(c.getRadius() + Math.random() * 
         (height - c.getRadius() * 2));
   }
}



PreviousNext

Related