JEditorPaneにソースコードをシンタックスハイライトして表示する
Total: 2838, Today: 2, Yesterday: 1
Posted by aterai at
Last-modified:
Summary
JEditorPaneのHTMLEditorKitにStyleSheetを設定して、ソースコードをシンタックスハイライト表示します。
Screenshot

Advertisement
Source Code Examples
private void loadFile(String path) {
try (Stream<String> lines = Files.lines(
Paths.get(path), StandardCharsets.UTF_8)) {
String txt = lines.map(s -> s.replace("&", "&")
.replace("<", "<")
.replace(">", ">"))
.collect(Collectors.joining("\n"));
editor.setText("<pre>" + prettify(engine, txt) + "\n</pre>");
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static String prettify(ScriptEngine engine, String src) {
try {
Object w = engine.get("window");
return (String) ((Invocable) engine).invokeMethod(
w, "prettyPrintOne", src);
} catch (ScriptException | NoSuchMethodException ex) {
ex.printStackTrace();
return "";
}
}
View in GitHub: Java, KotlinDescription
上記のサンプルでは、ScriptEngineでgoogle-prettify.jsを実行し、Openボタンで選択したソースコードをハイライト済みのHTMLテキストに変換してJEditorPaneで表示しています。
ScriptEngineでHTMLテキストに変換する前にソースコード中の&、<、>を文字実体参照に変換する必要があるHTMLEditorKitのCSSで色は3桁表記(color:#RGB) には対応していないため6桁表記(color:#RRGGBB)に変換して使用- First pass at a way to dodge newline issues in IE.の修正以降の
prettify.jsでは、prettyPrintOneの内部でDocument型のオブジェクトが使用されるようになったのでScriptEngine(Nashorn)のみでは実行不可- このため、このサンプルでは古いバージョンの
prettify.js(Fixed prettyPrintOne by removing requirement that a job have a source node. Fixes issues 133 and 134.)を添付して利用している - prettify.js(r120)
- このため、このサンプルでは古いバージョンの
Reference
- google/code-prettify: Automatically exported from code.google.com/p/google-code-prettify
- Rhinoでgoogle-code-prettifyを実行する
- Java access files in jar causes java.nio.file.FileSystemNotFoundException - Stack Overflow
- [JDK-8293776] Adds CSS 4 and 8 digits hex coded Color - Java Bug System