我正在尝试从网格开始创建用户界面。我在scenebuilder中构建了网格,现在我想使用控制器添加列和行。但是,由于网格不会更改大小,因此我的程序似乎未在控制器中运行Initialize()。这是我的主要课程:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的控制器类:
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);
}
Run Code Online (Sandbox Code Playgroud)
这是我第一次用javafx编写程序,对不起,我可能犯了一些简单的错误。
您正在调用静态 FXMLLoader.load(URL)
方法。由于它是静态方法,因此它实际上未引用FXMLLoader
您创建的实例,因此也未引用您设置的控制器。
调用load()
不带参数的实例方法:
final Parent root = loader.load();
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)