Copy and paste in codemirror.js embeded in javafx

2019-02-14 08:12发布

I'm creating simple editor in Java FX using codemirror.js library. I embeded codemirror editor in javafx using javafx.scene.web.WebView component, with the folowing html/js code:

<body>
<form>
   <textarea id="code" name="code">
   </textarea>
</form>
<script>
   var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true});
</script>
</body>

Codemirror editor itself supports undo, redo, cut, copy and paste.

I have also javafx main menue in my application and I want to add actions like copy or paste to it. I want to somehow "bind" this menue actions with my codemirror editor, so if user click e.g. paste from main menue, the content from clipboard will be added to the codemirror editor.

I solved this problem for undo and redo operations: codemirror has two js functions undo() and redo() and I can invoke they from java level via javafx.scene.web.WebView.executeScript method.

My question is how to handle cut, copy and paste operations? How to bind this operations from main menue with codemirror editor? I can't find any js functions in codemirror.js that can handle this oprations.

Any help appreciated and thanks in advance.

1条回答
姐就是有狂的资本
2楼-- · 2019-02-14 08:53

I've found solution: Codmirror doesn't have functions like cut, copy and past in API, but it allow to get and replace selected text, so I can write those operations by myself.

public void cut() {
    String selectedText = (String) webview.getEngine().executeScript(
            "editor.getSelection();");
    webview.getEngine().executeScript("editor.replaceSelection(\"\");");
    final Clipboard clipboard = Clipboard.getSystemClipboard();
    final ClipboardContent content = new ClipboardContent();
    content.putString(selectedText);
    clipboard.setContent(content);

}

public void copy() {
    String selectedText = (String) webview.getEngine().executeScript(
            "editor.getSelection();");
    final Clipboard clipboard = Clipboard.getSystemClipboard();
    final ClipboardContent content = new ClipboardContent();
    content.putString(selectedText);
    clipboard.setContent(content);
}

public void paste() {
    final Clipboard clipboard = Clipboard.getSystemClipboard();
    String content = (String) clipboard.getContent(DataFormat.PLAIN_TEXT);
    webview.getEngine().executeScript(String.format("editor.replaceSelection(\"%s\");", content));
}
查看更多
登录 后发表回答