Using stringWidth with html String

164 views Asked by At

This is probably a very easy question, but as I don't really know what I'm looking for, I couldn't succeed to find the solution...

I'm using a JLabel inside which I put a html string. My string is obtained by Jsoup Then, I want to resize the JLabel to make it fit the string. For that, I'm using the FontMetrics.stringWidth method which works fine... Except in the case I have special characters, such as "è", "ç", "ô", etc. In this case, the characters becomes sth like ô, or é, and the stringWidth takes it into account.

for instance, FontMetrics.stringWidth(HTMLFormating("é")) will give me the stringWidth of ("é") which is far longer... My expected result is that when I measure the length of "échec" for instance, I get the same result as for "echec"

What is the solution ? Is there a way to transform back the html string into a "normal" string ? Or should I use another method ?

Thanks for your help !

2

There are 2 answers

0
Andrew Thompson On BEST ANSWER

Just check the preferred size of the label once the String has been added.

1
Mike M On

You should probably post the code that you're using to resize the JLabel. I'll address that issue though because it's probably the one that causing your problem.

public void resize(String newText){
    label.setText(newText);
    label.setFont (font);
    int labelW = (int) Math.ceil (label.getPreferredSize().getWidth());
    int maxWidth = (int) Math.floor (panel.getSize().getWidth());
    if (labelW <= maxWidth)
        return;
    for (int k = 1 ; labelW > maxWidth ; k++) {
        Font labelFont = font.deriveFont (font.getSize() - k*1.0f);
        label.setFont (labelFont);
        labelW = (int) Math.ceil (label.getPreferredSize().getWidth());
    }
}