关于swing:Java-在包含HTML的JTextPane中更改字体

Java - Change font in a JTextPane containing HTML

我有一个JTextPane,并且在该JTextPane中有一些文本。但是,由于我一直在窗格中使用HTML,因此文本似乎已自动更改为Times New Roman。

我正在尝试将JTextPane中的字体类型设置为GUI的默认字体(如果不是HTML,则为JTextPane的字体)。但是我不能仅将字体设置为一种字体,因为它与操作系统不同,因此我想找到一种方法来获取默认字体,然后将必须的文本更改为默认字体。

为演示转换后如何将文本交换到Times New Roman,以下代码是我使用的格式。如何更改它以实现我的目标?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import javax.swing.JFrame;
import javax.swing.JTextPane;


public class GUIExample {

    public static void main(String[] args) {

        JFrame frame = new JFrame("My App");
        frame.setSize(300,300);
        JTextPane pane = new JTextPane();
        pane.setContentType("text/html");
        pane.setText("<html>This is some text!</html>");
        frame.add(pane);

        frame.setVisible(true);

    }

}

谢谢!


以下将解决问题:

1
 pane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true);

(请注意,JTextPane扩展了JEditorPane。)

更新(2016年8月):

为生存而设置的外观


最简单的方法可能是这样的:

1
string fontfamily = pane.getFont().getFamily();

这将为您提供默认字体。然后只需使用CSS:

1
pane.setText("<html><body style="font-family:" + fontfamily +""This is some text!</html>");


JComponent html渲染器使用其自己的字体,而不使用JComponent的字体。为了使组件能够呈现相同的效果,您需要在html字符串中设置字体属性。除其他外,您将需要设置字体系列,大小,粗体/斜体等。

作为示例,您可以执行以下操作:

1
2
3
4
JTextPane pane = new JTextPane();
Font font = pane.getFont();
pane.setContentType("text/html");
pane.setText("<html><font face="" + font.getFamily() +"" size="" + font.getSize() +""></font>This is some text!</html>");

创建一个为您执行此操作的函数将是微不足道的。向其传递一个JComponent和一个字符串,它将为您创建html文本,包括所有字体标签。