views:

273

answers:

5

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'd like to do is be able to control the line height/spacing between the two lines.

PS: I've also looked at using paragraphs instead of breaklines, but it's the same thing. And I don't know if you can do that within an html tag without using css (you can't use css within html code in a JLabel in Java Swing).

+1  A: 

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!

badpanda
I have to say this is probably going to be allot more robust then messing with the editor kit.
Justin
This may work if you only have 2 lines, but what if it's multiple lines?
Stephane Grenier
If it is multiple lines, I would use a Text Pane, with camickr's solution.
badpanda
+1  A: 

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.

camickr
+2  A: 

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.

Dave
Ya .. CSS support in Swing is currently pretty lame. The line-height property is modeled but not rendered. Javadoc for CSS shows which CSS properties are supported.http://java.sun.com/javase/6/docs/api/index.html?javax/swing/text/html/CSS.html
unhillbilly
Oh .. and thanks for the Swing HTML Preview link! :)
unhillbilly
Is there any way to do this without css? And thank you as well for the link!
Stephane Grenier
A: 

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)

iamrakesh
+1  A: 

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>");
unhillbilly