Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>See <a href="http://www.exampledepot.com/egs/javax.swing.text/style_HiliteWords.html" rel="nofollow noreferrer">Highlighting Words in a JTextComponent</a>.</p> <pre><code>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 while ((pos = text.indexOf(pattern, pos)) &gt;= 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&lt;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); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload