gpt4 book ai didi

java - 如何在 JavaFX 中组合 FXML 文件和组?

转载 作者:行者123 更新时间:2023-12-01 11:03:07 25 4
gpt4 key购买 nike

因此,我为学校制作的一个小游戏制作了一个 FXML 文件,其中有一些按钮和标签,并且有自己的 Controller 。现在我制作了一组矩形,并希望将其添加到与 fxml 文件相同的场景中。

button.getParent().getChildren().add(group);

我在这里编写的代码不起作用。有人知道如何在 fxml 文件中添加组或仅将其渲染在场景上吗?

在 2 个不同场景中渲染 fxml 和组确实有效,因此没有错误。

编辑:

应用程序类:

package retris;

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

/**
*
* @author Arno Vandersmissen, Casper Vranken, Rani Vanhoudt
*/
public class Retris extends Application {

private Stage stage;

@Override
public void start(Stage stage) throws Exception {

this.stage = stage;

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("FXMLRetris.fxml"));
Parent root = loader.load();

FXMLRetrisController controller = loader.getController();

controller.playMusic();

stage.setOnCloseRequest(e -> {
e.consume();
FXMLConfirmController confirm= new FXMLConfirmController();
if(confirm.close("Close?")){
Platform.exit();
}
});

Scene scene = new Scene(root);

stage.setTitle("Retris");
stage.setScene(scene);
stage.show();
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

最佳答案

一个Scene只能显示一个Parent一次。无论您想在 GUI 中显示什么,都将包含在 Parent 中。 。假设,正如您在评论中建议的那样,您想要在运行时更新该父级,您需要引用父级的任何子级,其中应包含您的 group of rectangles .

假设您的 fxml 文件的根元素是 AnchorPane ,并且您还想添加 group of rectangles到那个根。在您的 .fxml 文件中,您需要一个 fx:id 标记 <AnchorPane fx:id="myRoot">这允许您使用 @FXML 注释将元素注入(inject)到 Controller 类中。

public class MyController {
@FXML private AnchorPane myRoot;

@FXML private void createAndAddRectangles {
/**myRoot is already instantiated. you can simply add nodes to it at runtime
by using onAction="createAndAddRectangles" tag on a button in your .fxml file.**/
}
}

关于java - 如何在 JavaFX 中组合 FXML 文件和组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33186656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com