gpt4 book ai didi

java - FX :id and initialize() not running in javafx

转载 作者:行者123 更新时间:2023-12-01 16:46:18 27 4
gpt4 key购买 nike

我正在尝试创建一个用户界面,从网格开始。我在 scenebuilder 中构建了网格,现在想使用我的 Controller 添加列和行。然而,我的程序似乎没有在我的 Controller 中运行initialise(),因为网格没有改变大小。这是我的主要类(class):

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

这是我的 Controller 类:

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编写,所以我可能犯了一些简单的错误,抱歉。

最佳答案

您正在调用静态 FXMLLoader.load(URL) 方法。由于它是静态方法,因此它实际上并不引用您创建的 FXMLLoader 实例,因此它不会引用您设置的 Controller 。

调用不带参数的实例方法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);
}
}

关于java - FX :id and initialize() not running in javafx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49920102/

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