1

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();
        }

    }
  • `TextStyle` has a `color` parameter – Jorn Aug 10 '23 at 09:20
  • The logic is much more complicated than that. What if "keywords" are contained in comments? What about handling multi-line comments? The highlighting logic would need to be done every time a character is added/remove from the document. This is a big task and you are not going to get a solution here. You best bet is to try and find code you can insert into your program. – camickr Aug 10 '23 at 14:30

0 Answers0