• category: swing folder: SyntaxHighlightingEditorPane title: JEditorPaneにソースコードをシンタックスハイライトして表示する tags: [JEditorPane, HTMLEditorKit, StyleSheet] author: aterai pubdate: 2018-07-30T03:56:00+09:00 description: JEditorPaneのHTMLEditorKitにStyleSheetを設定して、ソースコードをシンタックスハイライト表示します。 image: https://drive.google.com/uc?export=view&id=1b_texG1scFcKnOIcUNUHQPdquKal_Fu6OQ

概要

JEditorPaneHTMLEditorKitStyleSheetを設定して、ソースコードをシンタックスハイライト表示します。

サンプルコード

private void loadFile(String path) {
  try (Stream<String> lines = Files.lines(
      Paths.get(path), Charset.forName("UTF-8"))) {
    String txt = lines.map(s -> s.replace("&", "&amp;")
                                 .replace("<", "&lt;")
                                 .replace(">", "&gt;"))
      .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, Kotlin

解説

上記のサンプルでは、ScriptEnginegoogle-prettify.jsを実行し、Openボタンで選択したソースコードをハイライト済みのHTMLテキストに変換してJEditorPaneで表示しています。

参考リンク

コメント