简体   繁体   English

在JTextArea或JTextPane中设置样式文本

[英]Styling text in a JTextArea or JTextPane

Basically, I have a JTextPane to hold some text which I wish to style. 基本上,我有一个JTextPane来保存一些我希望样式的文本。 JTextArea would have been better for me to use but I'm told you cannot style the text in these? JTextArea对我来说会更好用但是我告诉你不能在这些文本中设置样式吗?

However, the JTextPane doesn't seem to style properly. 但是,JTextPane似乎没有正确的样式。 For example, the following code is just returned with the HTML included: 例如,只返回包含HTML的以下代码:

public static void main(String[] args) {
    JFrame j = new JFrame("Hello!");
    j.setSize(200,200);
    JTextPane k = new JTextPane();
    k.setText("<html><strong>Hey!</strong></html>");
    j.add(k);
    j.setVisible(true);
}

I want to be able to just style some text in a JTextPane when a user interacts with the interface, but so far, it just returns the string with the HTML still in! 我希望能够在用户与界面交互时在JTextPane中设置一些文本的样式,但到目前为止,它只返回HTML仍在的字符串! Help! 救命!

If you want to diplaying Html contents in the JTextPane then you have to set for JTextPane#setContentType("text/html"); 如果你想在JTextPane中绘制Html内容,那么你必须为JTextPane设置#setContentType (“text / html”); , example here ,例如这里

EDIT: 编辑:

for JEditorPanes / JTextPanes is there another way by implements StyledDocument , MutableAttributeSet and with customized Highlighte r, example here 对于JEditorPanes / JTextPanes有另一种方法,通过实现StyledDocumentMutableAttributeSet和自定义Highlighte r,例如这里

am way is without using Html syntax 我没有使用Html syntax

让Java知道它将是使用setContentType方法的HTML。

k.setContentType("text/html"); 

I use a Look and Feel (Substance) and calling setContentType("text/html") has problems with the font displayed. 我使用外观(物质)并调用setContentType("text/html")与显示的字体有问题。 I solved it by calling: 我通过调用解决了它:

textPane.putClientProperty(JTextPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);

Another option is wrapping the HTML text in a JLabel . 另一种选择是将HTML文本包装在JLabel Following your example the code is: 按照您的示例,代码为:

JTextPane k = new JTextPane();
k.insertComponent(new JLabel("<html><strong>Hey!</strong></html>"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM