【问题标题】:Recoloring word while typed键入时重新着色单词
【发布时间】:2014-07-20 15:25:53
【问题描述】:

我想编写一个程序,我会重新着色特定的单词。

像这样:

嘿,我喜欢带骨头的胡萝卜。

我想让胡萝卜在键入时自动显示,将其设为蓝色。 哇,我在代码中这样做吗?

我已经试过了:

public void getWord(String whatword){
   if(jtextarea.contains(whatword){
      //Stuck on here
     }  

例如: 如果我输入这个:

我喜欢胡萝卜和金枪鱼。

我想将颜色从胡萝卜和金枪鱼更改为蓝色。 其他词需要保持黑色。

现在我不知道如何给这个词重新着色,也不知道这个 if 语句是否有效。 那么,我该如何解决呢?

对不起,我是荷兰人,所以你需要用这种语言来做,我想

【问题讨论】:

标签: java swing colors jtextarea


【解决方案1】:

JTextArea 仅用于包含纯文本,不能为某些单词着色。如果您希望能够为不同的单词着色,则需要使用JTextPaneJEditorPane

有关详细信息,请参阅此question。这个question 也可能有帮助

这是一个例子:

JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();

Style style = textPane.addStyle("I'm a Style", null);
StyleConstants.setForeground(style, Color.red);
String word = "Hello";

if (word.equals("Hello") {
    try {
        doc.insertString(doc.getLength(), word, style);
    } catch (BadLocationException ex) {
        ex.printStackTrace();
    }
} else {
    StyleConstants.setForeground(style, Color.blue);

    try {
        doc.insertString(doc.getLength(), word, style);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}

这会生成一个字符串word。如果word为"Hello",则显示为红色,否则显示为蓝色。

【讨论】:

  • 好吧,如果我使用 JTextPane,那我该怎么做呢?
  • 我现在添加了一个例子,看看链接的问题也可以告诉你如何使用JTextPanes
  • “那我该怎么做呢?” 这个问题的答案远远超出了 SO 的答案。这就是为什么我们有tutorials.. +1 来回答这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
  • 2016-02-23
相关资源
最近更新 更多