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

Java中如何实现首行居中且多行两端对齐的文本效果?

Java实现首行居中+多行两端对齐的文本效果

JTextArea仅支持整体文本对齐(左、右、居中),无法实现首行与其余行的混合对齐需求,推荐使用JTextPane(支持富文本样式)来实现,以下是具体解决方案:

实现思路

通过StyledDocument为文本的不同行设置独立样式:

  1. 定义两种段落样式:首行居中、其余行两端对齐
  2. 插入文本后,通过文档元素获取第一行的范围,为其应用居中样式
  3. 剩余行应用两端对齐样式

完整代码示例

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

public class MixedTextAlignment {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("首行居中+多行两端对齐");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(450, 300);

            JPanel displayPanel = new JPanel(new BorderLayout());
            JTextPane textPane = new JTextPane();
            textPane.setEditable(false);
            textPane.setFont(new Font("Arial", Font.PLAIN, 14));

            StyledDocument doc = textPane.getStyledDocument();
            // 定义首行居中样式
            Style centerStyle = doc.addStyle("Center", null);
            StyleConstants.setAlignment(centerStyle, StyleConstants.ALIGN_CENTER);
            // 定义两端对齐样式
            Style justifyStyle = doc.addStyle("Justify", null);
            StyleConstants.setAlignment(justifyStyle, StyleConstants.ALIGN_JUSTIFIED);

            // 测试文本
            String sentence = "Hello world, this is a sentence that is long enough to wrap into multiple lines. We need the first line to be centered, and all subsequent lines to be justified.";

            try {
                // 插入完整文本
                doc.insertString(0, sentence, null);
                // 获取文档行元素
                Element root = doc.getDefaultRootElement();
                int lineCount = root.getElementCount();
                
                if (lineCount > 0) {
                    // 为第一行应用居中样式
                    Element firstLine = root.getElement(0);
                    int start = firstLine.getStartOffset();
                    int end = firstLine.getEndOffset() - 1; // 排除换行符
                    doc.setParagraphAttributes(start, end - start, centerStyle, false);
                    
                    // 为剩余行应用两端对齐样式
                    if (lineCount > 1) {
                        int restStart = root.getElement(1).getStartOffset();
                        int restEnd = doc.getLength();
                        doc.setParagraphAttributes(restStart, restEnd - restStart, justifyStyle, false);
                    }
                }
            } catch (BadLocationException e) {
                e.printStackTrace();
            }

            displayPanel.add(new JScrollPane(textPane), BorderLayout.CENTER);
            frame.add(displayPanel);
            frame.setVisible(true);
        });
    }
}

关键说明

  • StyledDocument是JTextPane的核心,允许为文本的不同段落/区域设置独立样式
  • 通过getDefaultRootElement()获取文本的行元素,动态定位第一行的范围,避免手动拆分文本的局限性
  • 若文本仅一行,会自动只应用居中样式,无需额外判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:38:15