testFX.java:
public class testFX extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
try{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/testFX/view/test.fxml"));
System.out.println("after set location");
//PROBLEM
AnchorPane root = (AnchorPane)loader.load();
System.out.println("Does not happen");
testFXController listController = loader.getController();
listController.start();
Scene scene = new Scene(root, 200, 300);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
catch (Exception ex){
System.out.println("Error");
}
}
public static void main(String[] args) {
launch(args);
}
}
testFXController.java:
package testFX.view;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
public class testFXController {
@FXML ListView<String> listView;
private ObservableList<String> obsList;
public void start() {
// create an ObservableList
// from an ArrayList
obsList = FXCollections.observableArrayList("Giants", "Patriots", "Jaguars");
listView.setItems(obsList);
}
}
测试.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.ListView?>
<AnchorPane xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="view.testFXController">
<ListView fx:id="listView"
AnchorPane.topAnchor="10"
AnchorPane.leftAnchor="10"
AnchorPane.rightAnchor="10"
AnchorPane.bottomAnchor="10" />
</AnchorPane>
当我运行 testFX.java 时,系统打印:
after set location
Error
这是教授的代码,我似乎无法运行它。我意识到主要问题出在代码行 AnchorPane root = (AnchorPane)loader.load();
但我不知道如何解决这个问题,有人可以帮忙吗?
最佳答案
值 fx:controller
属性很可能是错误的(除非您的 Controller 类与发布的 Controller 类不同)
您要使用的 Controller :testFX.view.testFXController
fxml中的属性值:view.testFXController
!= testFX.view.testFXController
假设没有其他错误无法用问题中的信息重现,则修复属性值应该可行。
关于JavaFX fxml 加载器无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35237576/