Here is an example of how you could relocate your nodes in random locations :
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class RandomRelocateTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane box = new BorderPane();
AnchorPane mainPane = new AnchorPane();
addPanes(mainPane);
Button button = new Button("Randomize Location");
button.setOnAction(e -> {
randomizeLoc(mainPane);
});
box.setCenter(mainPane);
box.setBottom(button);
Scene scene = new Scene(box, 550, 450);
primaryStage.setScene(scene);
primaryStage.show();
}
// Add 15 rectangle to a specific location
private void addPanes(AnchorPane mainPane) {
for (int i = 0; i < 15; i++) {
Rectangle rec = new Rectangle();
rec.setStyle("-fx-border-color: black");
rec.setWidth(20);
rec.setHeight(20);
rec.relocate(50 + 20 * i + 5 * i, 10);
mainPane.getChildren().add(rec);
}
}
private void randomizeLoc(AnchorPane mainPane) {
double myMargins = 30;
double rectangleSize = 20;
double paneWidth = mainPane.getWidth() - myMargins - rectangleSize;
double paneHeight = mainPane.getHeight() - myMargins - rectangleSize;
// Get all the Nodes inside the AnchorPane
ObservableList<Node> childrens = mainPane.getChildren();
for (Node n : childrens) {
double x = myMargins + Math.random() * (paneWidth);
double y = myMargins + Math.random() * (paneHeight);
n.relocate(x, y);
}
}
}
Have a look at the randomizeLoc() and I am going to add some pictures explaining the logic of my calculations.

Edit : Above there is an example of a AnchorPane. The actual dimensions is the filled rectangle and the area we want to draw the Object is the Dotted Rectangle. Now the Math.random will give you a number between 0.0 and 1.0. First of all we want to be sure that we are inside the Dotted Area so the upper left corner is at (20,20) ( if we set the marginValue = 20) and the right down corner is at (width-20,height-20). So if we want to be exactly inside the dotted area we need to set X and y like :
x = 20 + Math.random() * (width-20);
y = 20 + Math.random() * (height-20);
Unfortunately if we get 1.0(or close to 1.0) from the Math.random() that mean that the Start of the rectangle is going to be at x,y = (width-20,height-20) and the rectangle has a size of 20x20 so the rectangle ( or a part of it, depending of the value of the random()) will be outside of the dotted area. So we need to subtract from the width and height the actual rectangle size. Thus we need to have :
x = 20 + Math.random() * (width -20 - 20); // if we say the rect is 20x20
y = 20 + Math.random() * (height -20 - 20);
So our area is now the dotted one subtracted by dashed line.