Google Tag Manager

2018/07/31

Syntax highlighting the source code in the JEditorPane

Code

// NG: color:#RGB
// OK: color:#RRGGBB
private void loadFile(String path) {
  try (Stream<String> lines = Files.lines(
      Paths.get(path), StandardCharsets.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 "";
  }
}

References

No comments:

Post a Comment