교육 목적으로 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>
그리고 컨트롤러 :이 단계에서 Label
가 초기화되지 않기 때문에
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 –