3

假设我有一个显示 HTML 文档的 JTextPane。

我希望在按下按钮时增加文档的字体大小。

不幸的是,这并不像看起来那么容易……我找到了一种更改整个文档字体大小的方法,但这意味着所有文本都设置为我指定的字体大小。我想要的是字体大小与文档中已有的大小成比例增加。

我是否必须遍历文档上的每个元素,获取字体大小,计算新大小并将其重新设置?我怎么能做这样的操作?什么是最好的方法?

4

3 回答 3

4

在您链接到的示例中,您会发现一些您正在尝试做的事情的线索。

线

StyleConstants.setFontSize(attrs, font.getSize());

更改 JTextPane 的字体大小并将其设置为您作为参数传递给此方法的字体大小。您要根据当前大小将其设置为新大小。

//first get the current size of the font
int size = StyleConstants.getFontSize(attrs);

//now increase by 2 (or whatever factor you like)
StyleConstants.setFontSize(attrs, size * 2);

这将导致 JTextPane 的字体大小加倍。你当然可以以较慢的速度增加。

现在你需要一个按钮来调用你的方法。

JButton b1 = new JButton("Increase");
    b1.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            increaseJTextPaneFont(text);
        }
    });

因此,您可以编写类似于示例中的方法,如下所示:

public static void increaseJTextPaneFont(JTextPane jtp) {
    MutableAttributeSet attrs = jtp.getInputAttributes();
    //first get the current size of the font
    int size = StyleConstants.getFontSize(attrs);

    //now increase by 2 (or whatever factor you like)
    StyleConstants.setFontSize(attrs, size * 2);

    StyledDocument doc = jtp.getStyledDocument();
    doc.setCharacterAttributes(0, doc.getLength() + 1, attrs, false);
}
于 2009-06-02T13:38:25.490 回答
1

您可能可以使用 css 并仅修改样式字体。

由于它按原样呈现 HTML,因此更改 css 类可能就足够了。

于 2009-06-02T12:27:34.307 回答
0

经过长时间的探索,我找到了一种方法来缩放显示 HTML 进出的 JTextPane 中的字体。

这是使 JTextPane 能够缩放字体的成员函数。它不处理 JTextPane 内的图像。

private void scaleFonts(double realScale) {
    DefaultStyledDocument doc = (DefaultStyledDocument) getDocument();
    Enumeration e1 = doc.getStyleNames();

    while (e1.hasMoreElements()) {
        String styleName = (String) e1.nextElement();
        Style style = doc.getStyle(styleName);
        StyleContext.NamedStyle s = (StyleContext.NamedStyle) style.getResolveParent();
        if (s != null) {
            Integer fs = styles.get(styleName);
            if (fs != null) {
                if (realScale >= 1) {
                    StyleConstants.setFontSize(s, (int) Math.ceil(fs * realScale));
                } else {
                    StyleConstants.setFontSize(s, (int) Math.floor(fs * realScale));
                }
                style.setResolveParent(s);
            }
        }
    }
}
于 2019-03-07T03:18:52.500 回答