sazzy4o
sazzy4o

Reputation: 3343

How do you add to an existing scene in javafx?

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?

Upvotes: 1

Views: 6093

Answers (2)

Kyte
Kyte

Reputation: 834

I would recommend a different approach entirely. If you are using the NetBeans IDE, you can download a tool called SceneBuilder. This application lets you build and edit simple or complex JavaFX applications.

As your application becomes more and more complex, it makes more sense to use a tool like SceneBuilder. I used SceneBuilder to create a fairly complex client GUI in less than an hour. Life in JavaFX is easier with NetBeans and SceneBuilder (and I'm a guy who prefers Eclipse!)

Upvotes: -1

brian
brian

Reputation: 10979

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();
    }
}

Upvotes: 3

Related Questions