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

如何为ArrayList列表项中的单个单词设置不同颜色?

How to Highlight a Specific Word in an ArrayList Item with Different Color

Hey there! Sounds like you need to display an ArrayList item ("Some important words") where only the word "important" is colored differently. Since an ArrayList itself is just a data storage structure, I assume you're working with a Swing JList (the common way to display ArrayList items in a UI). Here's a straightforward solution:

Step 1: Set up your ArrayList and JList

First, define your ArrayList with the text, then create a JList to display it:

import java.util.ArrayList;
import javax.swing.JList;

// Initialize your ArrayList
ArrayList<String> listData = new ArrayList<>();
listData.add("Some important words");

// Create JList from the ArrayList
JList<String> itemList = new JList<>(listData.toArray(new String[0]));

Step 2: Create a Custom Cell Renderer

To color part of the text, you'll need a custom ListCellRenderer that modifies how each list item is drawn. The easiest way is to use HTML in a JLabel (since Swing's JLabel supports basic HTML styling):

import javax.swing.DefaultListCellRenderer;
import javax.swing.JComponent;
import java.awt.Component;

class ColoredWordRenderer extends DefaultListCellRenderer {
    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        // Call the super method to handle default styling (selection colors, etc.)
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        
        // Check if the value is a string, then modify the text
        if (value instanceof String itemText) {
            // Replace "important" with a colored HTML span
            String styledText = itemText.replace(
                "important", 
                "<span style='color: #ff4444;'>important</span>"
            );
            // Wrap the text in HTML tags to enable styling
            setText("<html>" + styledText + "</html>");
        }
        
        return this;
    }
}

Step 3: Attach the Renderer to Your JList

Finally, set the custom renderer on your JList:

itemList.setCellRenderer(new ColoredWordRenderer());

Extra Tips

  • Change the Color: Swap #ff4444 (a red shade) with any valid CSS color name or hex code (like blue, #00cc66 for green).
  • Multiple Occurrences: The replace() method will color every instance of "important" in the string—perfect if you have items with the word repeated.
  • No HTML Alternative: If you don't want to use HTML, you could use a JTextPane as the renderer component, but that adds more complexity for simple color changes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:10:32