JavaFX无法设置Label或Text的文本

我不知道为什么这不起作用。我想设置标签或文本的文本。(如果有效的话,哪个都没关系)。标签保持不变。当我使用 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,但两者都不起作用。我还尝试初始化标签和文本。



 txtResult = new Text();

 lblResult = new Label();

我调试了代码。message 是一个字符串,包含正确的消息。


qq_花开花谢_0
浏览 30回答 1
1回答

阿波罗的战车

当您调用时不应创建控制器,FXMLLoader.load因为load将创建控制器。您也不应该使用 load 的静态版本。你的代码应该看起来像这样: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 是控制器的类名。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java