first line
s...">

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

I have the following JLabel code:

JLabel someJLabel = new JLabel("<html>first line<br>second line</html>"); someJLabel.setFont(new Font("Arial", Font.PLAIN, 16)); 

What I would like to do is control the height / spacing between two lines.

PS: I also considered using paragraphs instead of broken lines, but this is the same. And I don't know if you can do this in the html tag without using css (you cannot use css inside the html code in JLabel in Java Swing).

+4
source share
6 answers

This should work, but it is not. color: green works.

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

I think the line-height is not working. What would you do if you were using CSS, so you might not be able to do this. Here is a nice tool I found that you can use to check if your HTML will work fast.

+4
source

Check the setStyleSheet (...) method for HTMLEditorKit. I have never used it before, but I believe that it provides basic support.

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

 StyleConstants.setLineSpacing(...); 

Then you can change the foreground / background, etc., so that the text panel looks like a label.

+3
source

Hmm .. CSS in JLabel seems to work for me if I stick with the 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>"); 
+2
source

Because Java supports the <p> tag and the CSS margin attribute, you can use the following solution:

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

PS Now you do not need to close html tags.

+2
source

You can try using two labels and set the distance between them, as well as spaces using the LayoutManager. I like GridBoxLayout, myself.

Edit: GridBagLayout. Oops!

0
source

Does setting an empty border help e.g.

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

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

-1
source

Source: https://habr.com/ru/post/1313794/


All Articles