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

Java Swing JTextPane调用setParagraphAttributes设置行间距后自定义字体被重置问题

问题根因

调用setParagraphAttributes(set, true)时,第二个参数true代表完全覆盖JTextPane现有所有属性配置,你只在属性集里配置了行间距,没有包含自定义字体的相关设置,因此之前用setFont设置的自定义字体会被重置为系统默认字体。

修改方案

仅需要调整GUI类的代码逻辑,把自定义字体配置加入属性集,同时修改setParagraphAttributes的覆盖参数即可,修改后代码如下:

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.io.*;

public class GUI {
    public static final int sizeX = 1280;
    public static final int sizeY = 680;
    public static JTextPane textBox;

    public static JPanel createGui() {
        //创建面板
        JPanel mainPanel = new JPanel();
        JPanel textPanel = new JPanel();
        JPanel inventoryPanel = new JPanel();

        //配置面板基础属性
        mainPanel.setPreferredSize(new Dimension(sizeX, sizeY));
        textPanel.setBackground(Color.BLACK);
        inventoryPanel.setBackground(new Color(71, 22, 22));

        //提前声明字体变量,后续属性集要调用
        Font customFont = null;
        //加载自定义字体
        try {
            customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Main/resources/font.ttf")).deriveFont(10f);
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            ge.registerFont(customFont);

            textBox = new JTextPane();
            textBox.setFont(customFont);
        } catch (IOException|FontFormatException e) {
            System.out.println("<Error> 字体加载失败");
        }

        //配置文本属性,移动到字体加载完成之后
        SimpleAttributeSet attributeSet = new SimpleAttributeSet();  
        MutableAttributeSet set = new SimpleAttributeSet();
        StyleConstants.setForeground(attributeSet, Color.white);
        //新增:把自定义字体的配置加入字符属性集
        if (customFont != null) {
            StyleConstants.setFontFamily(attributeSet, customFont.getFamily());
            StyleConstants.setFontSize(attributeSet, customFont.getSize());
        }
        StyleConstants.setLineSpacing(set, 1.05f);

        //配置文本框属性
        textBox.setCharacterAttributes(attributeSet, true);
        //第二个参数改为false,不覆盖已有属性,避免重置字体
        textBox.setParagraphAttributes(set, false);
        textBox.setAutoscrolls(true);
        textBox.setEditable(true);
        textBox.setBackground(Color.black);
        textBox.setText("TextBox with some text I came up with to find out if it worked or not XD");

        //配置布局
        textPanel.add(textBox);
        mainPanel.setLayout(new GridLayout(1,2));
        textPanel.setLayout(new BoxLayout(textPanel, FlowLayout.LEADING));
        mainPanel.add(textPanel);
        mainPanel.add(inventoryPanel);

        return mainPanel;
    }
}

如果觉得行间距还是太小,可以把StyleConstants.setLineSpacing(set, 1.05f)里的1.05f调大,比如改成1.2f、1.5f,直到显示效果符合预期即可。

Window类的代码不需要做任何修改,直接用原来的就行。

内容的提问来源于stack exchange,提问作者KillerCube

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 21:09:01