How to set line spacing/height in a JLabel in Java Swing?

▼魔方 西西 提交于 2019-11-30 21:59:10

This should work, but it's not. color: green works though.

content.add(new JLabel("<html><p style=\"line-height: 150%;\">hi<br>world</p></html>"));

I guess line-height doesn't work. That's how you'd do it if you were to use CSS, so maybe you can't do it that way. Here's a nice tool I found which you can use to test if your HTML will work quickly.

Check out the setStyleSheet(...) method of the HTMLEditorKit. I've never used it before but I believe it provides some basic support.

Otherwise you can use a JTextPane to control the line spacing. I think you would use:

StyleConstants.setLineSpacing(...);

You can then change the foreground/background etc to make the text pane look like a label.

Hmm .. CSS in JLabel seems to work for me, if one sticks to supported properties. Try padding (or margin) and font-size:

someJLabel = new JLabel("<html><body><p style=\"padding:10; font-size:30\">First line</p><p style=\"padding:10; font-size:20\">Second line</p></body></html>");

Because of Java supports <p> tag and CSS margin attribute you can use next solution:

new JLabel("<html>first line<p style='margin-top:-5'>second line");

P.S. Now it is not required to close html tags.

You could try using two labels, and setting the distance between the two, as well as the whitespace, using a LayoutManager. I like GridBoxLayout, myself.

Edit: GridBagLayout. Whoops!

iamrakesh

Does setting empty border helps, like

label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

method syntax BorderFactory.createEmptyBorder(int top, int left, int bottom, int right)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!