How do you add to an existing scene in javafx?


Question

I would like to add more javafx objects to my scene but i am not sure how. I have tried looking it up but i could not find anything.

package application;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class Main extends Application {
    public void start(Stage primaryStage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/fxml/Main.fxml"));
            Scene scene = new Scene(root,600,400);
            // how would i add something here or further on?
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setResizable(false);
            primaryStage.setScene(scene);
            primaryStage.setTitle("Test");
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

For example how would i add a polygon to this?

1
0
5/26/2014 11:18:33 PM

Accepted Answer

You don't add them to scene, but to root, the Parent node of the scene. You have to change Parent to whatever type of node you're using in the FXML file. The default in netbeans is AnchorPane so that's what I used.

public void start(Stage primaryStage) throws Exception {
    try {
        AnchorPane root = FXMLLoader.load(getClass().getResource("fxml/Main.fxml"));
        Scene scene = new Scene(root, 600, 400);
        //how would i add something here or further on?
        root.getChildren().add(new Polygon(10,20,30,10,20,30));
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setResizable(false);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Test");
        primaryStage.show();
    } catch (Exception e) {
        e.printStackTrace();
      // don't leave me hanging bro!
        Platform.exit();
    }
}
2
5/26/2014 11:08:33 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon