【问题标题】:fx:id and initialize() not running in javafxfx:id 和 initialize() 未在 javafx 中运行
【发布时间】:2018-09-29 21:35:28
【问题描述】:

我正在尝试从网格开始创建用户界面。我在 scenebuilder 中构建了网格,现在我想使用我的控制器来添加列和行。但是,我的程序似乎没有在我的控制器中运行 initialise(),因为网格不会改变大小。 这是我的主要课程:

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 {
    //@Override 
    public void start(Stage primaryStage) {
        try {
            int width = 7;
            int height = 7;         
            final FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("GUI.fxml"));
            loader.setController(new GUIController(width, height));
            final Parent root = 
            FXMLLoader.load(getClass().getResource("GUI.fxml"));    
            final Scene scene = new Scene(root);
            primaryStage.setTitle("GUI");
            primaryStage.setScene(scene);
            primaryStage.show();            
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

这是我的控制器类:

import javafx.fxml.FXML;
import javafx.scene.layout.GridPane;

public class GUIController {

    private int width;
    private int height;

    public GUIController(int givenWidth, int givenHeight) {//runs this
        width = givenWidth;
        height = givenHeight;
    }


    @FXML 
    public void initialize() { //doesn't run this
        SetGrid.build(gridpane, width, height);
    }   

这是我第一次用 javafx 写东西,所以我可能犯了一些简单的错误,对不起。

【问题讨论】:

  • 你确定它没有运行吗?您是否尝试过将System.out.println(...) 作为initialize 的第一条语句?
  • 是的,当我打开它时我可以看到没有添加列(也没有触发我在 setGrid 的构建方法中的打印语句
  • 如果你一直坚持静态访问,你很快就会遇到更多麻烦。开始使用对象

标签: java javafx fxml


【解决方案1】:

您正在调用 static FXMLLoader.load(URL) 方法。由于它是一个静态方法,它实际上并没有引用您创建的FXMLLoader 实例,因此它也没有引用您设置的控制器。

改为不带参数调用实例方法load()

final Parent root = loader.load();

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 {
    @Override 
    public void start(Stage primaryStage) {
        try {
            int width = 7;
            int height = 7;         
            final FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("GUI.fxml"));
            loader.setController(new GUIController(width, height));

            final Parent root = loader.load();

            final Scene scene = new Scene(root);
            primaryStage.setTitle("GUI");
            primaryStage.setScene(scene);
            primaryStage.show();            
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 2014-07-04
相关资源
最近更新 更多