JTextPane突出显示文本

时间:2011-04-15 08:22:40

标签: java swing jtextpane

我可以从值开始将一些文本突出显示为JTextPane,并从另一个值开始 喜欢以下但是有黄色?

“” JTextPane 突出显示文字“”

感谢。

5 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);
    }
}

答案 2 :(得分:5)

是的,您可以通过 JTextPane 中的 setSelectionStart setSelectionEnd 来继承自 JTextPane

javadoc of JTextComponent.setSelectionStart

答案 3 :(得分:2)

您是否尝试过java的字符串比较方法

.equalsIgnoreCase("Search Target Text")

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

希望这可以帮助你Makky

答案 4 :(得分:0)

性能方面,最好将toUpperCase置于

String text = doc.getText(0,doc.getLength());

而不是在while循环中

但是感谢这个好榜样。