16

我可以将一些文本突出显示为JTextPane从一个值开始并从另一个值结束,如下所示,但颜色为黄色?

""JTextPane突出显示文本""

谢谢。

4

5 回答 5

18

通常有几种可能性,具体取决于“突出显示”的真正含义:-)

通过在文档级别更改任意文本部分的任何样式属性来突出显示,例如

    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setForeground(sas, Color.YELLOW);
    doc.setCharacterAttributes(start, length, sas, false);

通过 textPane 级别的荧光笔突出显示:

    DefaultHighlighter.DefaultHighlightPainter highlightPainter = 
        new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
    textPane.getHighlighter().addHighlight(startPos, endPos, 
            highlightPainter);
于 2011-04-15T09:52:07.740 回答
10

https://web.archive.org/web/20120530071821/http://www.exampledepot.com/egs/javax.swing.text/style_HiliteWords.html

JTextArea textComp = new JTextArea();

// Highlight the occurrences of the word "public"
highlight(textComp, "public");

// Creates highlights around all occurrences of pattern in textComp
public void highlight(JTextComponent textComp, String pattern)
{
    // First remove all old highlights
    removeHighlights(textComp);

    try
    {
        Highlighter hilite = textComp.getHighlighter();
        Document doc = textComp.getDocument();
        String text = doc.getText(0, doc.getLength());
        int pos = 0;

        // Search for pattern
        // see I have updated now its not case sensitive 
        while ((pos = text.toUpperCase().indexOf(pattern.toUpperCase(), pos)) >= 0)
        {
            // Create highlighter using private painter and apply around pattern
            hilite.addHighlight(pos, pos+pattern.length(), myHighlightPainter);
            pos += pattern.length();
        }
    } catch (BadLocationException e) {
    }
}

// Removes only our private highlights
public void removeHighlights(JTextComponent textComp)
{
    Highlighter hilite = textComp.getHighlighter();
    Highlighter.Highlight[] hilites = hilite.getHighlights();
    for (int i=0; i<hilites.length; i++)
    {
        if (hilites[i].getPainter() instanceof MyHighlightPainter)
        {
            hilite.removeHighlight(hilites[i]);
        }
    }
}

// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);

// A private subclass of the default highlight painter
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter
{
    public MyHighlightPainter(Color color)
    {
        super(color);
    }
}
于 2012-02-29T13:33:05.167 回答
4

是的,您可以通过JTextPane继承自JTextComponent函数setSelectionStartsetSelectionEnd 。

参见 JTextComponent.setSelectionStart 的 javadoc

于 2011-04-15T08:25:18.127 回答
2

你试过java的字符串比较方法吗

.equalsIgnoreCase("Search Target Text")

因为此方法允许搜索而不必考虑字符串的大小写这可能是您尝试实现的目标

希望这可以帮助你

于 2013-04-05T00:23:32.973 回答
0

性能方面最好把 toUpperCase 放在

字符串文本 = doc.getText(0, doc.getLength());

而不是在while循环中

但感谢你的好例子。

于 2014-02-23T11:10:54.533 回答