我正在尝试使用FXML标记创建自己的自定义JavaFX组件以及扩展HBox的控制器。无论出于何种原因,只是没有调用initialize()方法(我看不到调试输出)。这仅适用于我的自定义组件,我的所有其他控制器都按预期运行,并且始终在初始化。我不知道出了什么问题 - 这是我的代码。
NotificationItem.fxml(标记)
<fx:root type="javafx.scene.layout.HBox" xmlns:fx="http://javafx.com/fxml" spacing="5">
<ImageView fx:id="image" preserveRatio="true" fitWidth="60" />
<VBox alignment="center">
<Text text="notification" />
<Label fx:id="title" />
<Label fx:id="content" />
<Label fx:id="timestamp" />
</VBox>
</fx:root>
NotificationItem.java(控制器)
public class NotificationItem extends HBox {
public static final String FXML_FILENAME = "NotificationItem.fxml";
@FXML private ResourceBundle resources;
@FXML private ImageView image;
@FXML private Label title;
@FXML private Label content;
@FXML private Label timestamp;
private Notification notification;
private AbstractModel associatedModel;
public NotificationItem(Notification notification) {
this.notification = notification;
this.associatedModel = notification.getAssociatedModel();
FXMLHelper.loadFxml("/com/github/norbo11/topbuilders/fxml/" + FXML_FILENAME, this, this);
}
@FXML
public void initialize() {
System.out.println(notification.getType());
switch (notification.getType()) {
case ASSIGNMENT_CLOSE_TO_END:
break;
case EMPLOYEE_ASSIGNMENT_COMPLETE:
break;
case NEW_ASSIGNMENT:
break;
case NEW_MESSAGE:
Message message = (Message) associatedModel;
title.setText(resources.getString("home.notifications.new_message"));
content.setText(resources.getString("messages.sender") + ": " + message.getSender());
break;
case NEW_QUOTE_REQUEST:
break;
}
timestamp.setText(Util.formatDate(notification.getDate()));
}
}
用于加载我的FXML的程序(忽略返回值,在这种情况下不使用)
public static LoadedFXML loadFxml(String filename, Object root, Object controller) {
Log.info("Loading FXML: " + filename);
Parent loadedRoot = null;
AbstractController loadedController = null;
try {
FXMLLoader loader = new FXMLLoader(Main.getApp().getClass().getResource(filename));
if (root != null) loader.setRoot(root);
if (controller != null) loader.setController(controller);
if (!filename.equals(LoginScene.getAbsoluteFxmlFilename())) {
Employee user = Employee.getCurrentEmployee();
//If the user is logged in
if (user != null) {
Locale locale = Employee.getCurrentEmployee().getSettings().getLocale();
loader.setResources(ResourceBundle.getBundle("lang.lang", locale, ClassLoader.getSystemClassLoader()));
}
}
if (root == null) loadedRoot = loader.load();
if (controller == null) loadedController = loader.getController();
} catch (IOException e) {
e.printStackTrace();
}
return new LoadedFXML(loadedRoot, loadedController);
}
答案 0 :(得分:0)
我可能错了,因为我无法测试代码的大部分内容,但我认为问题在于:
public static LoadedFXML loadFxml(String filename, Object root, Object controller) {
if (root == null) loadedRoot = loader.load();
}
因为你是从构造函数调用的:
public NotificationItem(Notification notification) {
FXMLHelper.loadFxml(FXML_FILENAME, this, this);
}
root
不会为空,您无法加载FXML文件。事实上,你有相反的方法将根设置为几行。
只需更改条件即可调用initialize
:
if (root != null) loadedRoot = loader.load();