Customizing Text Color in JTextArea
JTextArea, a component commonly used to display plain text, lacks the flexibility to customize the color of specific text segments within a document. To achieve this level of control, consider using JTextPane instead.
JTextPane provides a powerful set of features for manipulating text formatting, including the ability to assign distinct colors to different portions of text. Here's how you can achieve this customization:
import java.awt.*; import javax.swing.*; import javax.swing.text.*; public class TextCustomization { public static void main(String[] args) { // Create a JTextPane for displaying the text JTextPane textPane = new JTextPane(); // Create a SimpleAttributeSet to control text attributes SimpleAttributeSet blueAttributeSet = new SimpleAttributeSet(); StyleConstants.setForeground(blueAttributeSet, Color.BLUE); SimpleAttributeSet greenAttributeSet = new SimpleAttributeSet(); StyleConstants.setForeground(greenAttributeSet, Color.GREEN); SimpleAttributeSet redAttributeSet = new SimpleAttributeSet(); StyleConstants.setForeground(redAttributeSet, Color.RED); SimpleAttributeSet orangeAttributeSet = new SimpleAttributeSet(); StyleConstants.setForeground(orangeAttributeSet, Color.ORANGE); // Set the text and apply color attributes to specific segments String text = "LOAD R1, 1\nDEC R1\nSTORE M, R1\nADD R4, R1,8"; textPane.setText(text); // Color specific words textPane.setParagraphAttributes(blueAttributeSet, true); textPane.setCaretPosition(0); textPane.setSelectedTextColor(Color.BLUE); textPane.setSelectionStart(0); textPane.setSelectionEnd(4); textPane.replaceSelection("LOAD"); textPane.setParagraphAttributes(greenAttributeSet, true); textPane.setCaretPosition(5); textPane.setSelectedTextColor(Color.GREEN); textPane.setSelectionStart(5); textPane.setSelectionEnd(7); textPane.replaceSelection("R1,"); textPane.setParagraphAttributes(redAttributeSet, true); textPane.setCaretPosition(9); textPane.setSelectedTextColor(Color.RED); textPane.setSelectionStart(9); textPane.setSelectionEnd(10); textPane.replaceSelection("M"); textPane.setParagraphAttributes(orangeAttributeSet, true); textPane.setCaretPosition(12); textPane.setSelectedTextColor(Color.ORANGE); textPane.setSelectionStart(12); textPane.setSelectionEnd(13); textPane.replaceSelection("R1,"); } }
In this example, the code snippet demonstrates how to change the color of specific keywords ("LOAD," "DEC," "STORE," "ADD," "R1," "M," and numbers) to designated colors (blue, green, red, and orange). By setting the appropriate attributes and replacing selected text segments, you can customize the appearance of text within the JTextPane.
The above is the detailed content of How can I customize text color within specific segments of a JTextArea?. For more information, please follow other related articles on the PHP Chinese website!