Implementing the Ace Code Editor in JavaFX

G L :

I am trying to make a code editor using JavaFX and want to use Ace. I saw an earlier post that used WebView to achieve this but I am a little lost on how to set up my project structure beforehand.

José Pereda :

The following is a very minimal implementation with JavaFX's WebView and the Ace editor.

To get started, I'll just use a few required js files from the Ace repository:

  • editor.html, this is the main entry. Download from here, and add it to the resources folder, like: src/main/resources/ace/editor.html.
  • mode-java.js, download from here, and add it to resources: src/main/resources/ace/js/mode-java.js.
  • theme-eclipse.js, download from here, and add it to resources: src/main/resources/ace/js/theme-eclipse.js.

Note that the above project structure corresponds with the use of Maven or Gradle build tools. To get started, I used this project as a reference.

Now edit the editor.html file, and replace the existing scripts with:

<script src="js/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/eclipse");
    editor.session.setMode("ace/mode/java");
</script>

Optionally, replace the javascript function with some java code, like:

<pre id="editor">package com.ace.editor;

import java.util.ArrayList;

public class AceEditor {

    /*
     * This is a demo
     */
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}</pre>

Finally, in your JavaFX code, add a WebView control, and load the editor:

WebView webView = new WebView(); 
WebEngine webEngine = webView.getEngine();
webEngine.load(getClass().getResource("/ace/editor.html").toExternalForm());
Scene scene = new Scene(webView, 600, 400);
...

Note that you will need to add the javafx.web module. This is using Gradle, but the same could be done with Maven.

javafx {
    version = "13"
    modules = [ 'javafx.web' ]
}

Build and run the project, and you should get the code editor:

Ace editor

More functionality can be added by modifying the editor.html file, and adding more js files, to extend the editor options. For instance, this shows you can add a statusbar.

EDIT

This is my project structure:

(It uses FXML as well, but doesn't change anything of the above).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306221&siteId=1