Swing的HTML支持基于HTML 3.2的一个子集,它并不完全支持CSS样式,CSS样式在所有表单中都包括line-height属性。
这个
line-height
如果Swing中的HTML呈现引擎识别出该属性,则该属性可能适用于相对值或百分比值。但是,由于它没有按预期工作,请考虑以下解决方法:
更换
<span>
元素a
<div>
并设置
线高度
在那里。有时,
div
元素与
线高度
变得更好。
JButton b = new JButton("<html><center><div style='line-height:" +
values[i] + "'>First line<br>and the second</div></html>");
如果line-height属性仍然不起作用,请使用显式的间距方法,如填充或添加
<br>
带有内联字体大小的标签。
不要依赖HTML样式,而是使用自定义样式自行调整文本呈现
JButton
或a
JLabel
具有多线支持。
例子:
import java.awt.*;
import javax.swing.*;
public class LineSpacingCustom extends JFrame {
public static final long serialVersionUID = 100L;
public LineSpacingCustom() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(480, 240);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
add(createBox("Decimal", new float[]{0.8f, 0.9f, 1.1f}));
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(LineSpacingCustom::new);
}
private Box createBox(String header, float[] spacings) {
Box box = Box.createVerticalBox();
JPanel p = new JPanel();
p.add(new JLabel(header, SwingConstants.CENTER));
box.add(p);
for (float spacing : spacings) {
JButton b = new LineHeightButton("First line\nand the second", spacing);
b.setPreferredSize(new Dimension(130, 60));
box.add(b);
}
return box;
}
}
class LineHeightButton extends JButton {
private final float lineSpacing;
public LineHeightButton(String text, float lineSpacing) {
super();
this.lineSpacing = lineSpacing;
setText(text);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setFont(getFont());
String[] lines = getText().split("\n");
int y = getInsets().top;
for (String line : lines) {
g2.drawString(line, getInsets().left, y += g2.getFontMetrics().getHeight() * lineSpacing);
}
}
}