简体   繁体   English

JTextArea或JTextPane设置突出显示的文本颜色

[英]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. 我正在尝试在TextArea或TextPane甚至其他任何一个中更改突出显示的颜色。

Note that I am looking for changing the color of: 请注意,我正在寻找更改颜色:

在此处输入图片说明

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. 我还看了一下JTextAreasetHighlighter()函数,但似乎我将需要输入一个匿名的Highlighter类,我绝对不知道如何实现所有重写。

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

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) (同样适用于JTextPane

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM