JLabel with HTML does not set width properly

2019-06-27 00:25发布

问题:

I am trying to set the width of a JLabel 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 have expected the JLabel to be 300 pixels wide, but in reality it is about 390 pixels wide. If I change the width specification to 200px, the resulting label is about 260 pixels wide.

What am I doing wrong?

回答1:

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

Edit: HTML in JLabel is very outdated



回答2:

You're setting the width of the text in the HTML, not the width of the JLabel.

Use the setPreferredSize method to set the width of the JLabel.

frame.pack();

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

Although it's better to let the JLabel size itself to allow the text to fit, as you've seen.



回答3:

Gilbert, I add your code and end up with this:

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

This simply does not work. I've also tried removing the HTML tags and the frame.setSize(600,600), neither of which produces what I'm looking for: A JLabel that is 200 pixels wide and has adjusted its height.