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

为字符串指定字符着色:求安卓Java代码对应的标准版Java实现方案

标准版Java实现字符串指定字符着色的方案

Android端的Spannable是安卓专属的UI文本样式类,标准版Java(JavaSE)环境下没有对应API,通常根据使用场景选择以下两种实现方式,原有匹配子串位置的正则逻辑可以完全复用:

方案1:JLabel + 内嵌HTML(最简单,适合简单展示场景)

适合纯展示、不需要文本编辑的场景,通过拼接HTML标签实现着色:

import javax.swing.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextHighlightDemo {
    public static void main(String[] args) {
        // 子串匹配逻辑和Android端完全一致
        ArrayList<Integer> positions = new ArrayList<>();
        Pattern p = Pattern.compile("mp"); // 替换为你要匹配的模式
        String originalText = "Simple Text, bumping , jumping";
        Matcher m = p.matcher(originalText);
        while (m.find()) {
            positions.add(m.start());
        }

        // 拼接带着色样式的HTML文本
        StringBuilder htmlBuilder = new StringBuilder("<html>");
        int lastCursor = 0;
        int keywordLength = 2; // 对应匹配关键词"mp"的长度
        for (int pos : positions) {
            // 拼接未匹配的普通文本
            htmlBuilder.append(originalText, lastCursor, pos);
            // 拼接着色的关键词
            htmlBuilder.append("<font color='blue'>")
                    .append(originalText, pos, pos + keywordLength)
                    .append("</font>");
            lastCursor = pos + keywordLength;
        }
        // 拼接剩余未匹配的文本
        htmlBuilder.append(originalText.substring(lastCursor));
        htmlBuilder.append("</html>");

        // 赋值给Swing的JLabel组件展示
        JFrame frame = new JFrame("着色演示");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JLabel(htmlBuilder.toString()));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

方案2:JTextPane + StyledDocument(灵活度高,适合复杂场景)

如果需要支持文本编辑、多样式混合等复杂需求,用Swing的富文本组件JTextPane实现:

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StyledTextHighlightDemo {
    public static void main(String[] args) {
        // 子串匹配逻辑和Android端完全一致
        ArrayList<Integer> positions = new ArrayList<>();
        Pattern p = Pattern.compile("mp"); // 替换为你要匹配的模式
        String originalText = "Simple Text, bumping , jumping";
        Matcher m = p.matcher(originalText);
        while (m.find()) {
            positions.add(m.start());
        }

        // 初始化富文本组件
        JTextPane textPane = new JTextPane();
        textPane.setText(originalText);
        // 定义蓝色样式
        StyleConstants.setForeground(textPane.addStyle("blueStyle", null), Color.BLUE);

        int keywordLength = 2; // 对应匹配关键词"mp"的长度
        for (int pos : positions) {
            // 给对应位置的文本应用样式
            textPane.getStyledDocument().setCharacterAttributes(
                    pos,
                    keywordLength,
                    textPane.getStyle("blueStyle"),
                    false
            );
        }
        textPane.setEditable(false); // 设为不可编辑即可当普通展示组件使用

        // 窗口展示
        JFrame frame = new JFrame("富文本着色演示");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textPane);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

注意事项

  • 上述两种都是JavaSE桌面端的原生实现,无需引入第三方依赖
  • 如果是Java Web场景,直接输出带style样式的HTML标签即可,逻辑和方案1的HTML拼接逻辑一致
  • 匹配关键词长度可以根据你的实际正则匹配结果动态调整,不需要固定为2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:57:02