Copy and paste into codemirror.js built into javafx application

I am creating a simple editor in Java FX using the codemirror.js library. I turned on the codemirror editor in javafx using the javafx.scene.web.WebView component, followed by the html / js code:

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

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

My app also has a javafx main menu, and I want to add actions like copy or paste to it. I want to somehow “link” these actions with my codemirror editor, so if the user clicks, for example. Paste from the main menu, the contents from the clipboard will be added to the codemirror editor.

I solved this problem for undo and redo operations: codemirror has two functions js undo () and redo (), and I can call them from the java level using the javafx.scene.web.WebView.executeScript method.

My question is how to handle cut, copy and paste operations? How to associate these operations with the main menu using the codemirror editor? I cannot find js functions in codemirror.js that can handle these fingerprints.

Any help is appreciated and thanks in advance.

+4
source share
1 answer

I found a solution: Codmirror does not have functions such as cut, copy and past in the API, but it allows you to get and replace the selected text, so I can write these operations 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)); } 
+6
source

Source: https://habr.com/ru/post/1398948/


All Articles