How to change text color in the JtextArea?

2019-01-01 02:20发布

I need to know how to do this:

Let's say: I have a code in the jtextArea like this,

LOAD R1, 1 DEC R1 STORE M, R1 ADD R4, R1,8

I wanted to change the color of LOAD, DEC, STORE and ADD to color BLUE R1, R4 to color green M to RED numbers to ORANGE

How to change the color of this text? These text were from notepad or can be directly type to the textArea.

Thank you in advance.

7条回答
一个人的天荒地老
2楼-- · 2019-01-01 02:50

For some basic coloring (the only thing you can do with JTextArea) you can change the background and foreground colors to something like this, but this will color all text of course:

    textArea.setBackground(Color.ORANGE);
    textArea.setForeground(Color.RED);

The result you get:

enter image description here

查看更多
泪湿衣
3楼-- · 2019-01-01 03:00

Use can either use a JEditorPane with HTML or write a custom Document that colors elements.

查看更多
与风俱净
4楼-- · 2019-01-01 03:00

Just another alternative. For the theory, see other answers.

This one creates attributes when adding text, instead of deriving the style like in the answer of nIcE cOw. The functionality is the same, as the pane will merge the attributes with any previously used attributes.

public final class SomeClass {
    private final JTextPane           textPane = new JTextPane();

    private void print(String msg, Color foreground, Color background) {
        AttributeSet attributes = new SimpleAttributeSet(textPane.getInputAttributes());
        StyleConstants.setForeground(attributes, foreground);
        StyleConstants.setBackground(attributes, background);

        try {
            textPane.getStyledDocument().insertString(textPane.getDocument().getLength(), msg, attributes);
        } catch (BadLocationException ignored) { }
    }
}

[Edit] changed back to insertString instead of replaceSelection because the latter fails when the pane is not editable

查看更多
琉璃瓶的回忆
5楼-- · 2019-01-01 03:03

You can't have different characters in different colors in a JTextArea (at least not without some complex hackery). Use a JTextPane or JEditorPane instead. Then you can access its StyledDocument:

StyledDocument sdoc = pane.getStyledDocument()

EDITED: changed to directly calling getStyledDocument, instead of casting the result of getDocument()

Call setCharacterAttributes on the StyledDocument to change the colors of individual characters or substrings.

查看更多
无色无味的生活
6楼-- · 2019-01-01 03:09

Just another alternative. For the theory, see other answers.

This one uses preconfigured styles as fields. Watch out when exposing these fields as they are, ehm, mutable.

public final class SomeClass {
    private final JTextPane           textPane = new JTextPane();
    private final MutableAttributeSet attributes1;
    private final MutableAttributeSet attributes2;

    public SomeClass() {
        attributes1 = new SimpleAttributeSet(textPane.getInputAttributes());
        StyleConstants.setForeground(attributes1, Color.BLACK);
        StyleConstants.setBackground(attributes1, Color.GREEN);
        attributes2 = new SimpleAttributeSet(textPane.getInputAttributes());
        StyleConstants.setForeground(attributes2, Color.WHITE);
        StyleConstants.setBackground(attributes2, Color.RED);
    }

    private void print(String msg, AttributeSet attributes) {
        try {
            textPane.getStyledDocument().insertString(textPane.getDocument().getLength(), msg, attributes);
        } catch (BadLocationException ignored) { }
    }
}

[Edit] changed back to insertString instead of replaceSelection because the latter fails when the pane is not editable

查看更多
浮光初槿花落
7楼-- · 2019-01-01 03:12

JTextArea is meant to entertain Plain Text. The settings applied to a single character applies to whole of the document in JTextArea. But with JTextPane or JEditorPane you have the choice, to colour your String Literals as per your liking. Here with the help of JTextPane, you can do it like this :

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.border.*;

import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class TextPaneTest extends JFrame
{
    private JPanel topPanel;
    private JTextPane tPane;

    public TextPaneTest()
    {
        topPanel = new JPanel();        

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);            

        EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));

        tPane = new JTextPane();                
        tPane.setBorder(eb);
        //tPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
        tPane.setMargin(new Insets(5, 5, 5, 5));

        topPanel.add(tPane);

        appendToPane(tPane, "My Name is Too Good.\n", Color.RED);
        appendToPane(tPane, "I wish I could be ONE of THE BEST on ", Color.BLUE);
        appendToPane(tPane, "Stack", Color.DARK_GRAY);
        appendToPane(tPane, "Over", Color.MAGENTA);
        appendToPane(tPane, "flow", Color.ORANGE);

        getContentPane().add(topPanel);

        pack();
        setVisible(true);   
    }

    private void appendToPane(JTextPane tp, String msg, Color c)
    {
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
        aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

        int len = tp.getDocument().getLength();
        tp.setCaretPosition(len);
        tp.setCharacterAttributes(aset, false);
        tp.replaceSelection(msg);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new TextPaneTest();
                }
            });
    }
}

here is the Output :

JTextPane

查看更多
登录 后发表回答