How to highlight a single word in a JTextArea [closed]
Asked Answered
F

1

6

I want to read in text the user inputs and then highlight a specific word and return it to the user. I am able to read in the text and give it back to the user, but I cant figure out how to highlight a single word. How can I highlight a single word in a JTextArea using java swing?

Fantinlatour answered 3/12, 2013 at 2:27 Comment(1)
You could use a Highlighter such as a DefaultHighlighter and call addHighlight(...) to your JTextArea, but if it is any bit more complicated than that, use a different text component.Scull
S
17

Use the DefaultHighlighter that comes with your JTextArea. For e.g.,

import java.awt.Color;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;

public class Foo001 {
   public static void main(String[] args) throws BadLocationException {
      
      JTextArea textArea = new JTextArea(10, 30);
       
      String text = "hello world. How are you?";
      
      textArea.setText(text);
      
      Highlighter highlighter = textArea.getHighlighter();
      HighlightPainter painter = 
             new DefaultHighlighter.DefaultHighlightPainter(Color.pink);
      int p0 = text.indexOf("world");
      int p1 = p0 + "world".length();
      highlighter.addHighlight(p0, p1, painter );
      
      JOptionPane.showMessageDialog(null, new JScrollPane(textArea));          
   }
}

addHighlight()

Parameters:

  • p0 - the beginning of the range >= 0
  • p1 - the end of the range >= p0
  • p - the painter to use for the actual highlighting

Returns:

an object that refers to the highlight

Throws:

BadLocationException - for an invalid range specification

Scull answered 3/12, 2013 at 2:39 Comment(3)
how can I highlighted a text by clicking on it and read it after that?Brahmana
@HoverCraftFullOfEels P0 && P1 what exactly means?Roryros
@Volazh: they are just dummy variables, p0 holding the index to the beginning of the highlighted word and p1 the index to the end of the word, as the code shows.Scull

© 2022 - 2024 — McMap. All rights reserved.