You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整多行JButton控件的行间距?

Swing多行按钮行间距问题

我尝试通过HTML文本创建多行按钮,使用HTML的line-height属性设置小数、像素和百分比值来调整垂直行间距,但完全没有效果。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LineSpacing extends JFrame {
  public static final long serialVersionUID = 100L;

  public LineSpacing() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(480, 240);
    setLayout(new FlowLayout());
    setLocationRelativeTo(null);

    add(createBox("Decimal", new String[]{"0.8", "0.9", "1.1"}));
    add(createBox("px", new String[]{"10px", "12px", "15px"}));
    add(createBox("%", new String[]{"85%", "95%", "110%"}));
    setVisible(true);
  }


  static public void main(String args[]) {
    EventQueue.invokeLater(LineSpacing::new);
  }


  private Box createBox(String header, String[] values) {
    Box box= Box.createVerticalBox();
    JPanel p= new JPanel();
    p.add(new JLabel(header, SwingConstants.CENTER));
    box.add(p);
    for (int i=0; i<3; i++) {
      JButton b= new JButton("<html><center><span style='line-height:"+
        values[i]+"'>First line<br>and the second</span></html>");
      b.setPreferredSize(new Dimension(130, 40));
      b.setMargin(new Insets(0,0,0,0));
      box.add(b);
    }
    return box;
  }

}

编辑补充

感谢Dewmith Mihisara提供的代码。我修改了他的LineHeightButton类,解决了文本重叠的问题。

修改后的代码片段如下:

// 调用部分
add(createBox("Decimal", new Dimension(130, 40),
            new int[]{-1, 0, 1, 2, 4, 6}));

// createBox方法调整
private Box createBox(String header, Dimension dim, int[] spacings) {
    // ... 原有逻辑省略
    JButton b = new LineHeightButton("First line\nand the second",
                                     dim, spacing);
    // ... 原有逻辑省略
}

// 自定义Button类
class LineHeightButton extends JButton {
    private final int lineSpacing;
    String text;

    public LineHeightButton(String text, Dimension dim, int lineSpacing) {
        super();
        this.lineSpacing = lineSpacing;
        this.text= text;
        setPreferredSize(dim);
        setMinimumSize(dim);
        setMaximumSize(dim);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setFont(getFont());
        String[] lines = text.split("\n");
        int y = getMargin().top+1;
        for (String line : lines) {
            g2.drawString(line, getInsets().left,
                y += g2.getFontMetrics().getHeight()-5 + lineSpacing);
        }
    }
}

目前还需实现文本居中,但这并非当前核心问题。

内容的提问来源于stack exchange,提问作者Jörg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 08:37:20