search
HomeJavajavaTutorialHow can I customize text color within specific segments of a JTextArea?

How can I customize text color within specific segments of a JTextArea?

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How to Share Data Between Steps in CucumberHow to Share Data Between Steps in CucumberMar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)