簡體   English   中英

如何在javafx中添加現有場景?

[英]How do you add to an existing scene in javafx?

我想在場景中添加更多javafx對象,但不確定如何。 我曾嘗試查找它,但找不到任何東西。

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

例如我將如何添加一個多邊形?

您無需將它們添加到場景,而是添加到場景的“父級”節點的根。 您必須將Parent更改為FXML文件中使用的任何類型的節點。 netbeans中的默認值是AnchorPane,這就是我所使用的。

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

我會完全推薦另一種方法。 如果使用的是NetBeans IDE,則可以下載一個名為SceneBuilder的工具。 該應用程序使您可以構建和編輯簡單或復雜的JavaFX應用程序。

隨着您的應用程序變得越來越復雜,使用諸如SceneBuilder之類的工具變得更加有意義。 我用SceneBuilder在不到一個小時的時間內創建了一個相當復雜的客戶端GUI。 使用NetBeans和SceneBuilder,JavaFX的生活更加輕松(而且我是一個更喜歡Eclipse的人!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM