You can place all those 3D objects in one collection, since all of them extend from Shape3D
.
You can create an ObservableList<Shape3D>
collection, and add each object to it when you create them. Then you can listen to changes in the collection, and add to the scene/subscene all the new objects.
This would be a sample of a controller with four buttons, where you can create random Box
or Sphere
3D objects, add them to the collection, and place them in a subscene.
Also you can perform operations with the full collection (translate or rotate them in this case).
public class FXMLDocumentController {
@FXML
private Pane pane;
private Group pane3D;
private PerspectiveCamera camera;
private ObservableList<Shape3D> items;
@FXML
void createBox(ActionEvent event) {
Box box = new Box(new Random().nextInt(200), new Random().nextInt(200), new Random().nextInt(200));
box.setMaterial(new PhongMaterial(new Color(new Random().nextDouble(),
new Random().nextDouble(), new Random().nextDouble(), new Random().nextDouble())));
box.setTranslateX(-100 + new Random().nextInt(200));
box.setTranslateY(-100 + new Random().nextInt(200));
box.setTranslateZ(new Random().nextInt(200));
items.add(box);
}
@FXML
void createSphere(ActionEvent event) {
Sphere sphere = new Sphere(new Random().nextInt(100));
sphere.setMaterial(new PhongMaterial(new Color(new Random().nextDouble(),
new Random().nextDouble(), new Random().nextDouble(), new Random().nextDouble())));
sphere.setTranslateX(-100 + new Random().nextInt(200));
sphere.setTranslateY(-100 + new Random().nextInt(200));
sphere.setTranslateZ(new Random().nextInt(200));
items.add(sphere);
}
public void initialize() {
camera = new PerspectiveCamera(true);
camera.setNearClip(0.1);
camera.setFarClip(10000);
camera.setTranslateZ(-1000);
pane3D = new Group(camera);
SubScene subScene = new SubScene(pane3D, 400, 400, true, SceneAntialiasing.BALANCED);
subScene.setFill(Color.ROSYBROWN);
subScene.setCamera(camera);
pane.getChildren().add(subScene);
items = FXCollections.observableArrayList();
items.addListener((ListChangeListener.Change<? extends Shape3D> c) -> {
while (c.next()) {
if (c.wasAdded()) {
c.getAddedSubList().forEach(i -> pane3D.getChildren().add(i));
}
}
});
}
@FXML
void rotateAll(ActionEvent event) {
items.forEach(s -> {
s.setRotate(new Random().nextInt(360));
s.setRotationAxis(new Point3D(-100 + new Random().nextInt(200),
-100 + new Random().nextInt(200), new Random().nextInt(200)));
});
}
@FXML
void translateAll(ActionEvent event) {
items.forEach(s -> {
s.setTranslateX(-100 + new Random().nextInt(200));
s.setTranslateY(-100 + new Random().nextInt(200));
s.setTranslateZ(new Random().nextInt(200));
});
}
}
