从JavaFX WebView中的Ace Editor获取代码

时间:2015-06-12 17:05:58

标签: java webview javafx ace-editor

我下载了Ace editor并将其放入我的本地计算机。我使用JavaFX使用WebView加载它。这是非常好的,但我如何检索编写的代码? (致Java String

1 个答案:

答案 0 :(得分:4)

只需通过调用

执行Javascript editor.getValue()即可
String code = (String)webView.getEngine().executeScript("editor.getValue()");

完整示例:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class AceEditorExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        WebView webView = new WebView();
        webView.getEngine().load(getClass().getResource("Ace.html").toExternalForm());
        Button saveButton = new Button("Save");
        saveButton.setOnAction(e -> {
            String code = (String) webView.getEngine().executeScript("editor.getValue()");
            System.out.println(code);
        });

        BorderPane.setAlignment(saveButton, Pos.CENTER);
        BorderPane.setMargin(saveButton, new Insets(10));
        primaryStage.setScene(new Scene(new BorderPane(webView, null, null, saveButton, null), 800, 600));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

使用Ace.html(例如):

<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
    #editor { 
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }
</style>
</head>
<body>
<h2>Edit code</h2>
<div id="editor">

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class AceEditorExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        WebView webView = new WebView();
        webView.getEngine().load(getClass().getResource("Ace.html").toExternalForm());
        Button saveButton = new Button("Save");
        saveButton.setOnAction(e -> {
            String code = (String) webView.getEngine().executeScript("editor.getValue()");
            System.out.println(code);
        });

        BorderPane.setAlignment(saveButton, Pos.CENTER);
        BorderPane.setMargin(saveButton, new Insets(10));
        primaryStage.setScene(new Scene(new BorderPane(webView, null, null, saveButton, null), 800, 600));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</div>

<script src="ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
    var editor = ace.edit("editor");
    editor.getSession().setMode("ace/mode/java");
</script>
</body>
</html>