【问题标题】:How do I change the colour of certain words when they are entered into a JTextPane? [closed]将某些单词输入 JTextPane 时如何更改它们的颜色? [关闭]
【发布时间】:2016-05-21 00:16:46
【问题描述】:

我看过几篇关于此的帖子,但似乎都没有。

我在 Java 编程论坛上有一个关于这个的帖子,请帮忙!:http://www.javaprogrammingforums.com/whats-wrong-my-code/47440-trying-make-simple-java-editor-having-trouble-changing-colour-words.html

【问题讨论】:

  • 问题是什么?
  • 当某些词被输入到 JTextPane 时,如何更改它们的颜色?抱歉,我应该更清楚这一点。
  • 请查看答案
  • 请先阅读 stackoverflow.com/help/how-to-ask,然后再提出下一个问题。
  • 看看this example

标签: java swing styles jtextpane


【解决方案1】:
DefaultStyledDocument document = new DefaultStyledDocument();
JTextPane textpane = new JTextPane(document);
StyleContext context = new StyleContext();
// build a style
Style style = context.addStyle("test", null);
// set some style color
StyleConstants.setForeground(style, Color.RED);
// add some data to the document
document.insertString(0, "", style);


OR




JTextPane pane = new JTextPane();
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setForeground(set, Color.red);
Document doc = pane.getStyledDocument();
doc.insertString(doc.getLength(), "Kleine ", set);

【讨论】:

  • 我在不同的函数中访问 doc.insertString 部分,然后是其他所有内容,并且我得到了 NullPointerException 。我有这样的调试: doc.insertString(0, "", style);每个不同的部分都在一个新行上,并且它在函数本身上。
  • 为什么需要doc in document.insertString(0, "", style);在不同的功能?
  • 我又尝试了一个选项,编辑了我的答案,请检查
  • 因为我有一种方法可以检测 Java 的“if”和“for”之类的东西。而另一个也不起作用。
猜你喜欢
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 2011-02-28
相关资源
最近更新 更多