繁体   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