爲了教育目的,我嘗試將熱鍵添加到我的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);
}
}
感謝您的回答。我自己在教javafx,只知道我的'Application'類不應該是'Controller'類。你在使用前一個onKeyPressed事件的時候內容窗格也是有效的,但我仍然會分開'Controller'和'Application'以正確的方式進行操作。其他讀者:我發現這個很好的解釋爲什麼分開他們: https://stackoverflow.com/questions/33303167/javafx-can-application-class-be-the-controller-class –