【问题标题】:How to create an FXML handler that accepts parameters?如何创建一个接受参数的 FXML 处理程序?
【发布时间】:2018-06-18 10:19:29
【问题描述】:

我正在用 JavaFXML 开发一个小型的假邮件客户端。 它提供了一个 Listview,其中包含写在 txt 文件中的消息、一个打印所选消息的 TextArea 和一些按钮。 这是主视图的图像:https://ibb.co/iKN2rm 我已经处理了“新消息”按钮,它正在启动一个新的 FXML 视图并且运行良好。

这是“New_Message”视图的图像:https://ibb.co/hQf5Bm

现在我正在尝试实现“回复”按钮,它应该启动与之前相同的视图(新消息),但设置从主视图获取的所有三个 TextFields 字符串,例如消息的文本、收件人和消息参数.

在新消息按钮处理程序下方:

private void handle_new(ActionEvent event) {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Client/Resources/new_utente1.fxml"));
        Parent root1 = (Parent) fxmlLoader.load();
        Stage stage = new Stage();
        stage.setTitle("New Message");
        stage.setScene(new Scene(root1));
        stage.show();
    } catch (Exception ecc) {
        System.out.println("ERROR: " + ecc.getMessage());
    }
}

我尝试实现 handle_reply 方法,但我无法添加参数,因为如果我这样做,FXML 文件将找不到该方法。

在 FXML 文件的一小部分下方:

<TextArea fx:id = "testo" editable="false" layoutX="283.0" layoutY="53.0" prefHeight="450.0" prefWidth="490.0" promptText="Select a message and it will be displayed here..." />
      <Button id="nuovo" layoutX="46.0" layoutY="521.0" onAction = "#handle_new" mnemonicParsing="false" prefHeight="25.0" prefWidth="173.0" text="New Message" />
      <Button id="reply" layoutX="283.0" layoutY="521.0" onAction = "#handle_reply" mnemonicParsing="false" prefHeight="25.0" prefWidth="132.0" text="Reply" />

我的问题是:如何实现前面描述的“handle_reply”方法? 谢谢

【问题讨论】:

标签: java javafx fxml


【解决方案1】:

创建一个控制器类

然后将这个类连接到你的视图

private void handle_new(ActionEvent event) {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Client/Resources/new_utente1.fxml"));
        Parent root1 = (Parent) fxmlLoader.load();
        CController ctr = fxmlLoader.getController();
        ctr.setLabelText("asdsad");
        Stage stage = new Stage();
        stage.setTitle("New Message");
        stage.setScene(new Scene(root1));
        stage.show();
    } catch (Exception ecc) {
        System.out.println("ERROR: " + ecc.getMessage());
    }
}

在你的控制器中你会做

public class CController implements Initializable {

    @FXML TextArea testo;

    @Override
    public void initialize(URL location, ResourceBundle resources) {}

    public void setLabelText(String text){testo.setText(text);}
}

【讨论】:

  • 控制器从 2.1 版开始不需要实现Initializable
【解决方案2】:

很遗憾,无法使用带参数的处理程序。您应该在每种情况下使用不同的处理程序。

前段时间也遇到过这个问题。作为一种解决方案,您可以执行小型重构以最大程度地减少代码重复。

如果你知道 javascript,你可以使用它而不是使用 java 处理程序:https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction_to_fxml.html#scripting

编辑:你也可以检查这个答案:https://stackoverflow.com/a/37902780/5572007(差不多)

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 2011-08-15
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多