Copy and paste in codemirror.js embeded in javafx application

谁都会走 提交于 2019-12-09 01:07:10

问题


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:


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));
}


来源:https://stackoverflow.com/questions/13929371/copy-and-paste-in-codemirror-js-embeded-in-javafx-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!