17

Can I highlight some text into a JTextPane starting from a value and ending from another value like the following but with the yellow color?

"" JTextPane highlight text ""

Thanks.

xdevel2000
  • 19,270
  • 35
  • 120
  • 188

5 Answers5

19

As often there are several possibilities, depending on what you really mean by "highlight":-)

Highlight by changing any style attributes of arbitrary text parts on the document level, something like

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

Highlight via a Highlighter on the textPane level:

    DefaultHighlighter.DefaultHighlightPainter highlightPainter = 
        new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
    textPane.getHighlighter().addHighlight(startPos, endPos, 
            highlightPainter);
kleopatra
  • 49,346
  • 26
  • 88
  • 189
  • 2
    Is the #2 a correct use of the Highlighter? The [Java Tutorial](http://docs.oracle.com/javase/tutorial/uiswing/components/textapi.html#carrots) defines it to be for "highlight the current selection" (cit.) which I think refers to getSelectedText(). – ignis Nov 01 '12 at 23:45
  • 2
    @ignis +1 for reading the tutorial :-) But I think it's poorly worded: it's whole purpose is to add custom highlighting. Read on in the api doc of Highlighter _allows to mark up the background with colored areas_ and its addHighlight _the beginning/end of the range_ – kleopatra Nov 02 '12 at 10:24
11

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);
    }
}
Matthew Cornell
  • 3,934
  • 3
  • 23
  • 38
Makky
  • 15,166
  • 17
  • 58
  • 81
  • @Makky-It works fine and thanks for the post But when searching "makky" it highlights only "makky" but not "Makky", "MAKKY". Is there any workaround for this problem? – John Jul 26 '12 at 08:01
  • @Makky-Thanks a lot. :). This clears my first hurdle. Another hurdle is of highlighting 2 different words. I am giving a search feature where user can search a sentence. When the sentence is searched as phrase all is fine. But when as separate words I am unable to highlight all the words separately. Would you put some light on this ?? – John Jul 26 '12 at 09:09
  • Hi . Glad that helped. Could you explain problem bit more ? – Makky Jul 26 '12 at 09:58
  • @Makky- say i searched "first hurdle" (as a phrase), then it is highlighting "first hurdle". These is bcoz these 2 words are consecutive, like a phrase. I want to search for both "first" and "hurdle" independently and highlight them too. – John Jul 26 '12 at 10:55
  • @Makky- I am using the code given above by you..;) nothing more than that – John Jul 26 '12 at 11:01
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/14454/discussion-between-john-and-makky) – John Jul 26 '12 at 11:13
  • ^ Sorry dude I don't know how to do that. There should be a way. By the way what the application you're trying to build may be I can help you @_ – Makky Jul 26 '12 at 15:02
5

Yes you can via the functions setSelectionStart and setSelectionEnd from JTextComponent which JTextPane inherits from.

see javadoc of JTextComponent.setSelectionStart

clamp
  • 30,396
  • 73
  • 193
  • 291
2

Did you try java's string comparison method

.equalsIgnoreCase("Search Target Text")

Because this method allows a search without having to take the case of a string into account This might be the ticket to what you are trying to achieve

Hope this helps you Makky

John
  • 21
  • 2
0

performance wise its better to put the toUpperCase on

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

rather than in the while loop

but thanks for the good example.

user667522
  • 29
  • 4