Search code examples
javajavafxrandommouseeventshapes

Changing location of shapes to a random location when mouse-clicked (javafx)


I need exactly what the title says. I've made 10 circles with different radius sizes, now I just need to make them shift their locations when I click on the scene with the mouse. I tried finding the solution here but none of the questions contain exactly what I need. Here's my code:

Random random = new Random();

    int x = 0;
    int y = 0;
    int radius = 0;

    @Override
    public void start(Stage primaryStage) {

        Group root = new Group();

        for (int i = 0; i <= 10; i++) {

            Circle circle = new Circle(x, y, radius);
            {
                radius = random.nextInt(66) + 10;
                x = random.nextInt(600 - 2 * radius) + radius;
                y = random.nextInt(400 - 2 * radius) + radius;
            }
            circle.setFill(Color.BLACK);
            circle.setStroke(Color.BLUE);

            root.getChildren().add(circle);
        }
        Scene scene = new Scene(root, 800, 500, Color.BEIGE);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();
    }

Solution

  • translate x y with mouse event

    Iterate through .getChildren().forEach() to get a child node of Group and translate it to random x y position . forEach() return a node object ,so it's not nescessary to cast it in this case

    random positions

    public class App extends Application {
        Random random = new Random();
    
        @Override
        public void start(Stage stage) {
              int x = 0;
        int y = 0;
        int radius = 0;
      
     Group root = new Group();
      
            for (int i = 0; i <= 10; i++) {
               
    
                Circle circle = new Circle(x, y, radius);
                {
                    radius = random.nextInt(66) + 10;
                    x = random.nextInt(600 - 2 * radius) + radius;
                    y = random.nextInt(400 - 2 * radius) + radius;
                }
                circle.setFill(Color.BLACK);
                circle.setStroke(Color.BLUE);
    
                root.getChildren().add(circle);
            }
            Scene scene = new Scene(root, 800, 500, Color.BEIGE);
            
            scene.setOnMouseClicked(e->{
            
            root.getChildren().forEach((n) -> {
                n.setTranslateX(random.nextInt(0,800));
                n.setTranslateY(random.nextInt(0,500));
            });
            
            });
            
            stage.setScene(scene);
            stage.show();
        }
    
        public static void main(String[] args) {
            launch();
        }
    
    }