有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是javafx的替代品。fxml。是否可以初始化以在场景开始时运行代码?

主要目标是在加载场景时运行代码,我知道Initializable是推荐的解决方案,我一直在使用它,但我遇到的问题是它不利于集成测试

我的initialize方法中的逻辑依赖于以前的场景,所以当我只加载这一个屏幕时,我会得到一些null指针异常,因为我期望存在的某些东西不存在

我没有办法模拟这些,因为使用TestFX,initialize方法在安装程序的第一行FXMLLoader loader = new FXMLLoader(getClass().getResource("test.fxml"));上运行

从那里开始,我将执行loader.getController();以访问生成的控制器并模拟某些类字段和内容,但问题是,在initialize方法运行之前,我不能这样做。这是第22条军规,因为要访问控制器javafx.fxml.FXMLLoader必须运行,但当它运行时,它会自动执行initialize方法,否则我需要模拟部分或生成预期信息

那么,我的选择是什么?有没有一种方法可以在场景开始时运行代码而不进行初始化

public class GameScreenController implements Initializable {

    private AppService appService;

    private PlayerService playerService;

    private DirectionService directionService;

    private RoomDirectionService roomDirectionService;

    @FXML
    private javafx.scene.control.Button closeButton;

    @FXML
    private Label goldAmount;

    @FXML
    private ImageView player;

    private final BooleanProperty wPressed = new SimpleBooleanProperty(false);
    private final BooleanProperty aPressed = new SimpleBooleanProperty(false);
    private final BooleanProperty sPressed = new SimpleBooleanProperty(false);
    private final BooleanProperty dPressed = new SimpleBooleanProperty(false);

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        this.appService = new AppService();
        this.directionService = new DirectionService();
        this.roomDirectionService = new RoomDirectionService(this.directionService);
        this.goldAmount.setText(String.valueOf(this.appService.getPlayerState().getGoldAmount()));
        this.playerService = new PlayerService(this.player, this.appService,
                this.roomDirectionService);
        this.playerService.moveX(this.appService.getPlayerState().getSpawnCoordinates()[0]);
        this.playerService.moveY(this.appService.getPlayerState().getSpawnCoordinates()[1]);
...

共 (0) 个答案