views:

565

answers:

2

Lets say that I have a JTextPane that is showing a HTML document.

I want that, on the press of a button, the font size of the document is increased.

Unfortunately this is not as easy as it seems... 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. What I want is that the font size is increased in a proportional scale to what was already in the document.

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

+1  A: 

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.

OscarRyz
+2  A: 

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