JTextArea is specifically designed for handling plain text, which means applying color changes to individual characters affects the entire document. However, using JTextPane or JEditorPane allows for more granular control, enabling you to color code different parts of your text.
To achieve this text customization:
JTextPane tPane = new JTextPane();
appendToPane(tPane, "Your Text", Color.YOUR_COLOR);
private void appendToPane(JTextPane tp, String msg, Color c) { StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); // Additional styling options (e.g., font, alignment): aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Your Font"); aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED); int len = tp.getDocument().getLength(); tp.setCaretPosition(len); tp.setCharacterAttributes(aset, false); tp.replaceSelection(msg); }
With JTextPane, you can now easily highlight specific parts of your text in different colors. This enhanced text customization can make your code easier to read and understand.
The above is the detailed content of How to Color Code Text in a Java Swing Application?. For more information, please follow other related articles on the PHP Chinese website!