设置 JTextArea 或 JTextPane 中文本的样式

发布于 01-02 14:43 字数 489 浏览 4 评论 0 原文

基本上,我有一个 JTextPane 来保存一些我希望设置样式的文本。 JTextArea 对我来说使用会更好,但我被告知你不能在其中设置文本样式?

但是,JTextPane 的样式似乎不正确。例如,以下代码仅返回包含 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);
}

当用户与界面交互时,我希望能够在 JTextPane 中设置某些文本的样式,但到目前为止,它仅返回仍包含 HTML 的字符串!帮助!

Basically, I have a JTextPane to hold some text which I wish to style. JTextArea would have been better for me to use but I'm told you cannot style the text in these?

However, the JTextPane doesn't seem to style properly. For example, the following code is just returned with the HTML included:

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! Help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不念旧人 2025-01-09 14:43:57

如果您想显示 中的 Html 内容JTextPane 那么你必须设置 JTextPane#setContentType( “text/html”);,例如 此处

编辑:

JEditorPanes / JTextPanes 是否有另一种方法通过实现 样式文档MutableAttributeSet 并带有自定义的 突出显示,示例 这里

的方法是不使用Html语法

If you want to diplaying Html contents in the JTextPane then you have to set for JTextPane#setContentType("text/html");, example here

EDIT:

for JEditorPanes / JTextPanes is there another way by implements StyledDocument, MutableAttributeSet and with customized Highlighter, example here

a.m. way is without using Html syntax

世界和平 2025-01-09 14:43:57

使用 "="">setContentType 方法。

k.setContentType("text/html"); 

Let Java know it will be HTML using setContentType method.

k.setContentType("text/html"); 
绿光 2025-01-09 14:43:57

我使用外观 (Substance) 并调用 setContentType("text/html") 时显示的字体出现问题。我通过调用解决了这个问题:

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

另一个选项是将 HTML 文本包装在 JLabel 中。按照您的示例,代码是:

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

I use a Look and Feel (Substance) and calling setContentType("text/html") has problems with the font displayed. I solved it by calling:

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

Another option is wrapping the HTML text in a JLabel. Following your example the code is:

JTextPane k = new JTextPane();
k.insertComponent(new JLabel("<html><strong>Hey!</strong></html>"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文