JTextPane highlight text
Asked Answered
S

5

16

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.

Swaggering answered 15/4, 2011 at 8:22 Comment(0)
D
18

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);
Duress answered 15/4, 2011 at 9:52 Comment(2)
Is the #2 a correct use of the Highlighter? The Java Tutorial defines it to be for "highlight the current selection" (cit.) which I think refers to getSelectedText().Lemaceon
@Lemaceon +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 rangeDuress
V
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);
    }
}
Vexed answered 29/2, 2012 at 13:33 Comment(7)
@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?Beerbohm
@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 ??Beerbohm
Hi . Glad that helped. Could you explain problem bit more ?Vexed
@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.Beerbohm
@Makky- I am using the code given above by you..;) nothing more than thatBeerbohm
let us continue this discussion in chatBeerbohm
^ 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 @_Vexed
M
4

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

see javadoc of JTextComponent.setSelectionStart

Melodeemelodeon answered 15/4, 2011 at 8:25 Comment(0)
B
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

Beerbohm answered 5/4, 2013 at 0:23 Comment(0)
S
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.

Shlomo answered 23/2, 2014 at 11:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.