如何为ArrayList列表项中的单个单词设置不同颜色?
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 (likeblue,#00cc66for 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
JTextPaneas the renderer component, but that adds more complexity for simple color changes.
内容的提问来源于stack exchange,提问作者Vladimir Gusev

