2014-03-13 68 views
0

所以,我在我的程序中有一个JTextArea,并且正在追加一些文本。 我试图仅仅使附加字符串中的一个粗体,而没有使所有JTextArea中的文本变为粗体。似乎没有办法,至少没有我能找到的方法来编辑字符串的字体,而无需将其添加到JLabel(我宁愿不这样做)。为单个字符串设置字体?

任何人都知道解决这个问题?

谢谢你的时间。

回答

1

使用的JTextPane代替JTextArea中。通过在此组件中嵌入文本作为html,您可以更自由地设置文本的样式。看到这个例子:

JTextPane myTextPane = new JTextPane(); 
myTextPane.setContentType("text/html"); 
StringBuilder stringBuilder = new StringBuilder(); 
stringBuilder.append("<html>"); 
stringBuilder.append("<b>bold text </b>"); 
stringBuilder.append("normal text"); 
stringBuilder.append("</html>"); 


myTextPane.setText(stringBuilder.toString()); 
+0

在JTextPane类中似乎没有附加方法。 – Shaun

+0

我得等到明天再试一试。 (因为我哥哥在睡觉,踢出了我的房间)>。> – Shaun

+0

很遗憾没有。看来,当我使用myTextPane.setContentType(“文本/ HTML”);该字符串不会出现。 – Shaun

3

最好的解决方法:不要使用JTextArea,这是一个用于轻松显示简单单一文本文本的组件。而应使用更强大的文本组件之一,如JEditorPane或JTextPane。请在教程一看:

+0

好的。我会尽力回复你。谢谢。 – Shaun