通过热键更新标签时的Javafx NPE
问题描述:
为了教育目的,我尝试将热键添加到我的javafx应用程序中。使用我的示例代码,我无法通过热键访问我的标签。使用按钮我可以调用完全相同的方法更新我的标签成功。通过热键更新标签时的Javafx NPE
的观点:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="62.0" prefWidth="91.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fx.probleme.SampleViewController">
<children>
<Label id="label" fx:id="label" layoutX="14.0" layoutY="45.0" text="Label" />
<Button layoutX="20.0" layoutY="14.0" mnemonicParsing="false" onAction="#updateText" text="Button" />
</children>
</AnchorPane>
而且控制器:
package fx.probleme;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
public class SampleViewController extends Application {
@FXML
Label label;
@FXML
void updateText() {
label.setText(label.getText() + "+");
}
@Override
public void start(Stage stage) throws Exception {
Parent parent = FXMLLoader.load(this.getClass().getResource("SampleView.fxml"));
Scene scene = new Scene(parent);
scene.setOnKeyPressed((final KeyEvent keyEvent) -> {
if (keyEvent.getCode() == KeyCode.NUMPAD0) {
updateText();
}
});
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
答
你得到NullPointerException
,因为在这个阶段,Label
没有初始化,初始化在initialize
完成。 首先你把你的主类和你的控制器类混合在一起,你可能想分开它们,设置一个控制器implements Initializable
,然后在initialize
方法中你可以调用组件的任何方法,因为在其中注解了所有的组件由@FXML
初始化。在你的情况下,在启动方法尚未初始化。你也可能不想使用场景的方法,而不是你可以添加事件,动作到你的内容窗格,在你的情况下,到AnchorPane
。
我建议将控制器类与主类分开,并实现Initializable
。这有助于您更好地了解应用程序,您可以看到组件的初始化位置,您确定要使用其方法,而无需NPE。
如果你不想做一个单独的类(推荐),你可以在.fxml
文件AnchorPane
添加fx:id
,那么你可以将方法添加到onKeyPressed
像你这样的按钮。
感谢您的回答。我自己在教javafx,只知道我的'Application'类不应该是'Controller'类。你在使用前一个onKeyPressed事件的时候内容窗格也是有效的,但我仍然会分开'Controller'和'Application'以正确的方式进行操作。其他读者:我发现这个很好的解释为什么分开他们: https://*.com/questions/33303167/javafx-can-application-class-be-the-controller-class –