Search code examples
javaswinghighlightjtextareajtextpane

JTextArea or JTextPane Set Highlighted Text Color


I am trying to change the color of a the highlight in either TextArea or TextPane or even any others.

Note that I am looking for changing the color of:

enter image description here

And not the text.

I have also took a look at the JTextArea's setHighlighter() function but it seems that I will need to input an anonymous Highlighter class which I have absolutely no idea how to implement all the overrides.

jta.setHighlighter(new Highlighter() {
    @Override
    public void removeHighlight(Object tag) {
        // TODO Auto-generated method stub

    }
    @Override
    public void removeAllHighlights() {
        // TODO Auto-generated method stub

    }
    @Override
    public void paint(Graphics g) {
        // TODO Auto-generated method stub

    }
    @Override
    public void install(JTextComponent c) {
        // TODO Auto-generated method stub

    }
    @Override
    public Highlight[] getHighlights() {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void deinstall(JTextComponent c) {
        // TODO Auto-generated method stub

    }
    @Override
    public void changeHighlight(Object tag, int p0, int p1)
            throws BadLocationException {
        // TODO Auto-generated method stub

    }
    @Override
    public Object addHighlight(int p0, int p1, HighlightPainter p)
            throws BadLocationException {
        // TODO Auto-generated method stub
        return null;
    }
});

Solution

  • If you mean the "normal" highlight color (when you drag your mouse over the text), this can simply be achieved by

    textArea.setSelectionColor(Color.LIGHT_GRAY);
    

    (or whatever color you want it to have.)

    If you want to programmatically highlight a character sequence in your text area:

    String searchedWord = "word";
    int pos1 = textArea.getText().indexOf(searchedWord);
    int pos2 = pos1 + searchedWord.length();
    try {
        textArea.getHighlighter().addHighlight(pos1, pos2,
                new DefaultHighlighter.DefaultHighlightPainter(Color.LIGHT_GRAY));
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
    

    (The same works for a JTextPane too)