如何突出显示JTextArea中的单个单词 [英] How to highlight a single word in a JTextArea

查看:226
本文介绍了如何突出显示JTextArea中的单个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文本中读取用户输入,然后突出显示特定单词并将其返回给用户。我能够阅读文本并将其返回给用户,但我无法弄清楚如何突出显示单个字。如何使用java swing突出显示JTextArea中的单个单词?

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?

推荐答案

使用JTextArea附带的DefaultHighlighter。例如,

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

这篇关于如何突出显示JTextArea中的单个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆