JLabel with HTML doesn't set width

I am trying to set the JLabel width using an HTML div tag.

Consider the following code:

import javax.swing.*;

public class Xyzzy extends JFrame{
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Xyzzy frame = new Xyzzy();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));

                String s = "x ";
                for (int i=0; i<200; ++i)
                    s += "x ";

                JLabel jl = new JLabel("<html><div style=\"width: 300px;\">" + s + "</div></html>");

                frame.add(jl);

                frame.setSize(600, 600);
                frame.setVisible(true);
            }
        });
    }
}

I would expect JLabel to have a width of 300 pixels, but in fact it is about 390 pixels wide. If I change the width specification to 200 pixels, the resulting label will be about 260 pixels wide.

What am I doing wrong?

+3
source share
3 answers

This HTML code is too complicated for JLabel (support only part of the HTML specification) http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JLabel.html The
size of the components depends on the layout. I prefer MigLayout http://www.miglayout.com a simple tutorial

: HTML JLabel

+6

HTML, JLabel.

setPreferredSize JLabel.

frame.pack();

Dimension d = label.getSize();
d.width = width;
label.setPreferredSize(d);

JLabel, , .

+2

, :

import javax.swing.*;
import java.awt.*;

public class Xyzzy extends JFrame{
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Xyzzy frame = new Xyzzy();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));

                String s = "x ";
                for (int i=0; i<200; ++i)
                    s += "x ";

                JLabel jl = new JLabel("<html>" + s + "</html>");

                frame.add(jl);
                frame.pack();

                Dimension d = jl.getSize();
                d.width = 200;
                jl.setPreferredSize(d);

                frame.setSize(600, 600);

                frame.setVisible(true);
            }
        });
    }
}

. HTML frame.setSize(600 600), , : JLabel 200 .

0

All Articles