增加显示HTML文本的JTextPane的字体大小

问题描述 投票:3回答:3

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

我想要的是,只需按一下按钮,文档的字体大小就会增加。

不幸的是,这并不像看起来那么容易...... I found a way to change the font size of the whole document, but that means that all the text is set to the font size that I specify。我想要的是字体大小按照与文档中已有的比例增加。

我是否必须遍历文档中的每个元素,获取字体大小,计算新大小并将其设置回来?我该怎么办这样的手术?什么是最好的方法?

java swing jtextpane
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);
}

1
投票

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

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


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);
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.