如何从WebEngine中的javascript调用JavaFX的UI变量?

chaim770:

我正在开发一个需要基于用户输入(在中ComboBox读取本地文件并将其显示在WebView中的应用程序我正在尝试从JavaScript调用JavaFX UI中的变量,但它不起作用。

我创建了一个getMonthIndex()用Java代码调用的函数,该函数返回ComboBox的输入,并且应该以适当的名称接收文件。我正在尝试将此函数导入JavaScript代码,但似乎未包含在JavaScript代码中。

如果您可以向我解释如何从JavaFX UI获取参数并在JavaScript代码中使用它。

提前非常感谢您可以提供的任何帮助。

我的Controller.java:

public class Controller {

    ObservableList<String> months = FXCollections.observableArrayList
                    ("Tishrei", "Cheshvan", "Kislev", "Tevet", "Shevat", "Adar",
                    "Nisan", "Iyar", "Sivan", "Tammuz", "Av", "Elul");

    public ComboBox<String> month;
    public WebView webView;

    public String getMonthIndex() {
        ReadOnlyIntegerProperty listIndex = month.getSelectionModel().selectedIndexProperty();
        return String.format("%02d", listIndex.getValue());
    }

    public long linesCount(String scanFile) {
        if (scanFile.length() < 80) {
            return scanFile.length() / 15;
        } else {
            return scanFile.length() / 24;
        }
    }

    @FXML
    public void initialize() {
        month.setItems(months);

        webView.setContextMenuEnabled(false);

        WebEngine webEngine = webView.getEngine();
        Controller controller = new Controller();
        JSObject win = (JSObject) webEngine.executeScript("window");
        win.setMember("app", controller);

        month.setOnAction(event -> {
            String loadFile = this.getClass().getResource("index.html").toString();
            webEngine.load(loadFile);
        });
    }
}

我的index.html(由WebEngine上传):

<html>
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>

    <body onload="readTextFile()">
        <div id="text">
        </div>
        <script type="text/javascript">
            function readTextFile() {
                var xhr, i, text, lines;
                xhr = new XMLHttpRequest();
                xhr.open('GET', app.getMonthIndex()+'.txt', true);
                xhr.send(null);
                xhr.onreadystatechange = function(){
                    text = xhr.responseText;
                    lines = text.split("\n");
                    var allText = "";
                    for(i = 0; i < lines.length; i++){
                        allText += lines[i]+"<br>";
                    }
                    document.getElementById("text").innerHTML = allText;
                }
            }
        </script>
    </body>
</html>
James_D:

您正在创建的新实例,该实例Controller与UI完全没有连接,并将其传递给Web引擎:

    Controller controller = new Controller();
     JSObject win = (JSObject) webEngine.executeScript("window");
    win.setMember("app", controller);

相反,只需传递当前实例:

    // Controller controller = new Controller();
    JSObject win = (JSObject) webEngine.executeScript("window");
    win.setMember("app", this);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章