JTextArea 替代方案中的自訂文字著色
在JTextArea 中,應用文字格式會影響整個文檔,而不是特定字元或特定字元或特定字元部分。若要實現自訂文字著色,請考慮使用 JTextPane 或 JEditorPane 等替代元件。
使用JTextPane 自訂文字著色
JTextPane 允許您為文字的特定部分設定不同的顏色:
import java.awt.Color; import java.awt.Insets; import java.awt.event.EmptyBorder; import javax.swing.JTextPane; import javax.swing.text.AttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; public class TextColoringDemo { public void setTextColors() { JTextPane textPane = new JTextPane(); textPane.setBorder(new EmptyBorder(new Insets(10, 10, 10, 10))); StyleContext styleContext = StyleContext.getDefaultStyleContext(); AttributeSet blueAttributeSet = styleContext.addAttribute( SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLUE ); AttributeSet greenAttributeSet = styleContext.addAttribute( SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.GREEN ); AttributeSet redAttributeSet = styleContext.addAttribute( SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED ); AttributeSet orangeAttributeSet = styleContext.addAttribute( SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.ORANGE ); // Set the color of specific text sections textPane.setCharacterAttributes(blueAttributeSet, true); textPane.replaceSelection("LOAD R1, 1\n"); textPane.setCharacterAttributes(blueAttributeSet, true); textPane.replaceSelection("DEC R1\n"); textPane.setCharacterAttributes(blueAttributeSet, true); textPane.replaceSelection("STORE M, R1\n"); textPane.setCharacterAttributes(blueAttributeSet, true); textPane.replaceSelection("ADD R4, R1,8\n"); textPane.setCharacterAttributes(greenAttributeSet, true); textPane.replaceSelection("R1\n"); textPane.setCharacterAttributes(greenAttributeSet, true); textPane.replaceSelection("R4\n"); textPane.setCharacterAttributes(redAttributeSet, true); textPane.replaceSelection("M\n"); textPane.setCharacterAttributes(orangeAttributeSet, true); textPane.replaceSelection("1\n"); textPane.setCharacterAttributes(orangeAttributeSet, true); textPane.replaceSelection("8\n"); } }
這種方法允許您自訂任何指定文字部分的顏色JTextPane 元件。
以上是如何在 Java Swing 中超越 JTextArea 實現自訂文字著色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!