简体   繁体   中英

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?

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

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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM