I am building my own code editor in java. How do I add syntax coloring like other code editors in it? I am able to add syntax highlighting like one we can do in Word or Excel (in which highlight background).
Here is my function for syntax highlighting:
private void addSyntaxHighlighting() {
StyledDocument doc = textPane.getStyledDocument();
Style keywordStyle = doc.addStyle("Keyword", null);
StyleConstants.setForeground(keywordStyle, Color.BLUE);
Style stringStyle = doc.addStyle("String", null);
StyleConstants.setForeground(stringStyle, Color.GREEN);
Style commentStyle = doc.addStyle("Comment", null);
StyleConstants.setForeground(commentStyle, Color.GRAY);
Pattern[] patterns = {
Pattern.compile("\\b(if|else|while|for|class|public|private)\\b"),
Pattern.compile("\".*?\""),
Pattern.compile("//.*")
};
try {
String content = textPane.getText();
doc.remove(0, doc.getLength());
doc.insertString(0, content, null);
for (Pattern pattern : patterns) {
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
Style style;
if (pattern.pattern().equals("\\b(if|else|while|for|class|public|private)\\b")) {
style = keywordStyle;
} else if (pattern.pattern().equals("\".*?\"")) {
style = stringStyle;
} else {
style = commentStyle;
}
doc.setCharacterAttributes(start, end - start, style, false);
}
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}