Increasing the font size of a JTextPane that displays HTML text

一个人想着一个人 提交于 2019-12-04 14:03:47

In the example that you linked to you will find some clues to what you are trying to do.

The line

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

changes the font size of the JTextPane and sets it to the size of the font that you pass as a parameter to this method. What you want to to set it to a new size based on the current size.

//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);

This will cause the font of the JTextPane double in size. You could of course increase at a slower rate.

Now you want a button that will call your method.

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

So you can write a method similar to the one in the example like this:

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);
}

You could probably use css and modify only the styles font.

Since it renders th HTML as it is, changing the css class may be enough.

After exploring for a long time, I've found a way to zoom the fonts in a JTextPane that displays HTML in and out.

Here's the member function that enables a JTextPane to scale the fonts. It does not handle the images inside the 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);
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!