How to highlight a single word in a JTextArea [closed]

早过忘川 提交于 2019-12-06 07:39:08

问题


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?


回答1:


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));          
   }
}


来源:https://stackoverflow.com/questions/20341719/how-to-highlight-a-single-word-in-a-jtextarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!