簡體   English   中英

JavaFX 無法設置 Label 的文字或文字

[英]JavaFX can't set the text of Label or Text

我不知道為什么這不起作用。 我想設置一個 Label 或 Text 的文本。 (不管它是否有效)。 label 保持不變。 當我使用 Text 時,應用程序會崩潰......

@FXML
    public Text txtMessage;
    @FXML
    public Text txtTitle;
    @FXML
    public Text txtResult;

    @FXML
    public Label lblResult;


    public void display(String title, String message) throws IOException {
        txtResult = new Text();
        lblResult = new Label();
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        Parent root= FXMLLoader.load(getClass().getResource("/Alertbox.fxml"));
        lblResult.setText("message");

        stage.setTitle(title);
        stage.setScene(new Scene(root));
        stage.show();
    }

它有2個參數。 我嘗試添加@FXML,或刪除@FXML,但兩者都不起作用。 我還嘗試初始化 label 和文本。


 txtResult = new Text();
 lblResult = new Label();

我調試了代碼。 message 是一個字符串,包含正確的消息。

調用FXMLLoader.load時不應創建 controller,因為load會創建 controller。 您也不應該使用 static 版本的負載。 您的代碼應該看起來像:

public static ControllerClass display(String title, String message) throws IOException {
    Stage stage = new Stage();
    stage.initModality(Modality.APPLICATION_MODAL);
    FXMLLoader loader = new FXMLLoader();
    Parent root= loader.load(getClass().getResource("/Alertbox.fxml"));
    ControllerClass controller = loader.getController();    
    controller.lblResult.setText("message");
    stage.setTitle(title);
    stage.setScene(new Scene(root));
    stage.show();
    return controller;

}

這可能仍然不完全正確,但它應該為您指明正確的方向。

請注意,ControllerClass 是 controller 的 class 名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM