0

In the following example, I first try to layout the text of the label by using the getPrefferedSize method, and then I use the resulting width and height to layout the text again in a style tag.

However, with each new layout, the width and height of the label are increasing progressively (just to be sure I set the padding, border and margins to zero).

Does anyone knows a way to overcome this (i.e. setting the width and height in a style tag that results in the same width and height returned from getPrefferedSize) ?

I tried several things, e.g using SwingUtilities.layoutCompoundLabel, or the guidelines presented in JLabel with HTML does not set width properly, but nothing worked as expected.

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class Test  
    {
    public static void main (String args[])
    {
        String text = "TEST <br> TEST2";
        JLabel localrenderer = new JLabel("");
        String labeltext = String.format("<html><div style=\"padding:0px;margin:0px;border:0px;\">%s</div><html>", text);
        localrenderer.setText(labeltext);
        int width1 = localrenderer.getPreferredSize().width;
        int height1 = localrenderer.getPreferredSize().height;
        System.out.println("FIRST run: "+width1+"-"+height1);

        labeltext = String.format("<html><div style=\"padding:0px;margin:0px;border:0px;height:%dpx;width:%dpx\">%s</div><html>", height1, width1, text);
        JLabel localrenderer2 = new JLabel(labeltext);
        width1 = localrenderer2.getPreferredSize().width;
        height1 = localrenderer2.getPreferredSize().height;
        System.out.println("SECOND run: "+width1+"-"+height1);

        labeltext = String.format("<html><div style=\"padding:0px;margin:0px;border:0px;height:%dpx;width:%dpx\">%s</div><html>", height1, width1, text);
        JLabel localrenderer3 = new JLabel(labeltext);
        width1 = localrenderer3.getPreferredSize().width;
        height1 = localrenderer3.getPreferredSize().height;
        System.out.println("THIRD run: "+width1+"-"+height1);     

        JFrame testframe = new JFrame();
        JPanel testpanel = new JPanel();

        testpanel.add(localrenderer);
        testpanel.add(localrenderer2);
        testpanel.add(localrenderer3);
        testframe.add(testpanel);
        testframe.pack();
        testframe.setVisible(true);
    }
}

EDIT: Now also displaying the labels. Though the display is not a real problem, but setting and getting a property of a JLabel containing HTML.

Community
  • 1
  • 1
JohnWaine
  • 1
  • 1
  • Can you please show the resulting HTML? In the meantime, please check if this helps: https://stackoverflow.com/questions/10686910/jlabel-with-html-does-not-set-width-properly?lq=1 – connexo Jan 21 '15 at 09:54
  • Hi connexo, I checked the link you sent, and it did not help. I will adapt the code to display the labels asap. – JohnWaine Jan 22 '15 at 12:19

0 Answers0