我正在尝试使用 JavaFX 制作代码编辑器并希望使用 Ace 。我之前看到一篇文章使用 WebView 来实现此目的,但我对如何预先设置项目结构有点迷失。
最佳答案
以下是使用 JavaFX 的 WebView 和 Ace 编辑器的非常简单的实现。
首先,我将使用 Ace repository 中的一些必需的 js 文件。 :
editor.html
,这是主条目。从here下载,并将其添加到资源文件夹中,例如:src/main/resources/ace/editor.html
。mode-java.js
,从here下载,并将其添加到资源:src/main/resources/ace/js/mode-java.js
。theme-eclipse.js
,从here下载,并将其添加到资源:src/main/resources/ace/js/theme-eclipse.js
。
请注意,上述项目结构与 Maven 或 Gradle 构建工具的使用相对应。首先,我使用了这个 project作为引用。
现在编辑 editor.html
文件,并将现有脚本替换为:
<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>
(可选)用一些 java 代码替换 javascript 函数,例如:
<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>
最后,在 JavaFX 代码中添加一个 WebView
控件,并加载编辑器:
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
webEngine.load(getClass().getResource("/ace/editor.html").toExternalForm());
Scene scene = new Scene(webView, 600, 400);
...
请注意,您需要添加 javafx.web
模块。这是使用 Gradle,但同样可以使用 Maven 完成。
javafx {
version = "13"
modules = [ 'javafx.web' ]
}
构建并运行项目,您应该获得代码编辑器:
可以通过修改 editor.html
文件并添加更多 js 文件来添加更多功能,以扩展编辑器选项。例如,this显示您可以添加状态栏。
编辑
这是我的项目结构:
(它也使用 FXML,但不会改变上述任何内容)。
关于java - 在 JavaFX 中实现 Ace 代码编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58466288/