Increase JTextPane font size displaying HTML text

Let's say I have a JTextPane that shows an HTML document.

I want the button to increase the font size of the document.

Unfortunately, this is not as simple as it seems ... I found a way to change the font size of the entire document, but this means that everything in the text has the font size that I specify . I want the font size to be scaled proportionally to what was already in the document.

Do I need to iterate over each element of the document, get the font size, calculate the new size and set it back? How can I do such an operation? What is the best way?

+3
source share
2 answers

In the example that you linked to you, you will find some tips on what you are trying to do.

Line

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

resizes the font of the JTextPane and sets its font size, which you pass as a parameter to this method. What do you want to set 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 result in a double JTextPane font size. You could, of course, grow more slowly.

Now you need 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 following example:

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);
}
+4
source

Perhaps you can use css and change only the font of styles.

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

+1
source

Source: https://habr.com/ru/post/1709590/


All Articles