gpt4 book ai didi

java - 替代默认的 JTextPane 字体呈现

转载 作者:行者123 更新时间:2023-11-30 03:53:31 24 4
gpt4 key购买 nike

兄弟,考虑以下简单的 html 内容。

<html>

<head>
<style>.foot{color:red} .head{color:black}</style>
</head>

<body>
<span id="xx" style="font-family:consolas">Hola!</span><br/>
<span id="xk" style="font-family:tahoma">Hola!</span>
</body>

</html>

现在我有一个 swing 应用程序,我想用 JTextPane 显示上述代码,但我想知道 JTextPane 如何加载 consolas tahoma 字体打印 Hola 文本数据。

我想覆盖默认字体渲染,应使用 courier new 字体代替 consolas,并使用 arial 代替 tahoma

我不喜欢替换内容和 html 内容,我喜欢用 JTextPane 渲染方法来完成,也许会覆盖某些东西,IDK。
现在我该如何克服它?< br/>提前致谢。

最佳答案

您可能正在寻找: JEditorPane#HONOR_DISPLAY_PROPERTIES (Java Platform SE 8)

Key for a client property used to indicate whether the default font and foreground color from the component are used if a font or foreground color is not specified in the styled text.

textPane.setFont(new Font("courier new", Font.PLAIN, 12));
textPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);

编辑你是说像这样吗?

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;

public class IgnoreStyleTest {
private static final String HTMLTEXT =
"<html><head><style>.foot{color:red} .head{color:black}</style></head>"
+ "<span id='xx' style='font-family:consolas'>Hola! consolas</span><br/>"
+ "<span id='xk' style='font-family:tahoma'>Hola! tahoma</span>";
private final JTextPane textPane1 = new JTextPane();
private final JTextPane textPane2 = new JTextPane();
private JComponent makeUI() {
textPane1.setContentType("text/html");
textPane1.setText(HTMLTEXT);

//Font font = new Font("courier new", Font.PLAIN, 12);
textPane2.setContentType("text/html");
textPane2.setFont(new Font("courier new", Font.PLAIN, 32));
textPane2.setDocument(new HTMLDocument() {
@Override public Font getFont(AttributeSet attr) {
StyleContext styles = (StyleContext) getAttributeContext();
//return styles.getFont(attr);
//return font;
Font f = styles.getFont(attr);
String ff = f.getFamily();
System.out.println(ff);
//if ("".equals(ff)) { //...
return textPane2.getFont(); //Ignore: style font-family
}
});
textPane2.setText(HTMLTEXT);

JPanel p = new JPanel(new GridLayout(0, 1));
p.add(new JScrollPane(textPane1));
p.add(new JScrollPane(textPane2));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new IgnoreStyleTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

关于java - 替代默认的 JTextPane 字体呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23815172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com