如何更改JTextArea中的文本颜色?

时间:2012-03-10 23:11:33

标签: java swing colors jtextarea jtextcomponent

我需要知道如何做到这一点:

让我们说:我在JTextArea中有一个像这样的代码:

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

我想将LOADDECSTOREADD的颜色更改为蓝色 R1R4为绿色 RED M 数字到ORANGE

如何更改此文字的颜色? 这些文本来自记事本,或者可以直接键入文本区域。

7 个答案:

答案 0 :(得分:77)

JTextArea旨在招待Plain Text。应用于单个字符的设置适用于JTextArea中的整个文档。但是,您可以选择JTextPaneJEditorPane,根据自己的喜好为String Literals着色。在JTextPane的帮助下,你可以这样做:

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();
                }
            });
    }
}

这是输出:

JTextPane

答案 1 :(得分:20)

因为Highlighter可能使用JTextArea(或Html),此API实现了针对样式文本的缩减选项

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class TextPaneHighlighting {

    private static final long serialVersionUID = 1L;
    private Highlighter.HighlightPainter cyanPainter;
    private Highlighter.HighlightPainter redPainter;

    public TextPaneHighlighting() {
        JFrame frame = new JFrame();
        JTextPane textPane = new JTextPane();
        textPane.setText("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n");
        JScrollPane scrollPane = new JScrollPane(textPane);
        frame.add(scrollPane, BorderLayout.CENTER);//  Highlight some text
        cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan);
        redPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
        try {
            textPane.getHighlighter().addHighlight(0, 3, DefaultHighlighter.DefaultPainter);
            textPane.getHighlighter().addHighlight(8, 14, cyanPainter);
            textPane.getHighlighter().addHighlight(19, 24, redPainter);
        } catch (BadLocationException ble) {
        }
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(300, 200));
        frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TextPaneHighlighting tph = new TextPaneHighlighting();
            }
        });
    }
}

JTextPane相比,选项更具变量,例如荧光笔,使用Html或没有Html,Font,或者通过使用Html或直接将其他JComponent放入其中(也知道JTextArea,但是......)

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class Fonts implements Runnable {

    private String[] fnt;
    private JFrame frm;
    private JScrollPane jsp;
    private JTextPane jta;
    private int width = 450;
    private int height = 300;
    private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    private StyledDocument doc;
    private MutableAttributeSet mas;
    private int cp = 0;
    private Highlighter.HighlightPainter cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan);
    private Highlighter.HighlightPainter redPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
    private Highlighter.HighlightPainter whitePainter = new DefaultHighlighter.DefaultHighlightPainter(Color.white);
    private int _count = 0;
    private int _lenght = 0;

    public Fonts() {
        jta = new JTextPane();
        doc = jta.getStyledDocument();
        jsp = new JScrollPane(jta);
        jsp.setPreferredSize(new Dimension(height, width));
        frm = new JFrame("awesome");
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setLayout(new BorderLayout());
        frm.add(jsp, BorderLayout.CENTER);
        frm.setLocation(100, 100);
        frm.pack();
        frm.setVisible(true);
        jta.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        fnt = ge.getAvailableFontFamilyNames();
        mas = jta.getInputAttributes();
        new Thread(this).start();
    }

    @Override
    public void run() {
        for (int i = 0; i < fnt.length; i++) {
            StyleConstants.setBold(mas, false);
            StyleConstants.setItalic(mas, false);
            StyleConstants.setFontFamily(mas, fnt[i]);
            StyleConstants.setFontSize(mas, 16);
            dis(fnt[i]);
            try {
                Thread.sleep(75);
            } catch (Exception e) {
                e.printStackTrace();
            }
            StyleConstants.setBold(mas, true);
            dis(fnt[i] + " Bold");
            try {
                Thread.sleep(75);
            } catch (Exception e) {
                e.printStackTrace();
            }
            StyleConstants.setItalic(mas, true);
            dis(fnt[i] + " Bold & Italic");
            try {
                Thread.sleep(75);
            } catch (Exception e) {
                e.printStackTrace();
            }
            StyleConstants.setBold(mas, false);
            dis(fnt[i] + " Italic");
            try {
                Thread.sleep(75);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        jta.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }

    public void dis(String s) {
        _count++;
        _lenght = jta.getText().length();
        try {
            doc.insertString(cp, s, mas);
            doc.insertString(cp, "\n", mas);
        } catch (Exception bla_bla_bla_bla) {
            bla_bla_bla_bla.printStackTrace();
        }
        if (_count % 2 == 0) {
            try {
                jta.getHighlighter().addHighlight(1, _lenght - 1, cyanPainter);
            } catch (BadLocationException bla_bla_bla_bla) {
            }
        } else if (_count % 3 == 0) {
            try {
                jta.getHighlighter().addHighlight(1, _lenght - 1, redPainter);
            } catch (BadLocationException bla_bla_bla_bla) {
            }
        } else {
            try {
                jta.getHighlighter().addHighlight(1, _lenght - 1, whitePainter);
            } catch (BadLocationException bla_bla_bla_bla) {
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Fonts fs = new Fonts();
            }
        });
    }
}

答案 2 :(得分:3)

使用可以将JEditorPane与HTML一起使用,也可以编写一个自定义文档来为元素着色。

答案 3 :(得分:2)

JTextArea中不能有不同颜色的不同字符(至少没有一些复杂的hackery)。请改用JTextPane或JEditorPane。然后,您可以访问其StyledDocument

StyledDocument sdoc = pane.getStyledDocument()

已编辑已更改为直接调用getStyledDocument,而不是转换getDocument()的结果

setCharacterAttributes上调用StyledDocument以更改单个字符或子字符串的颜色。

答案 4 :(得分:1)

对于一些基本的着色(你可以用JTextArea做的唯一的事情),你可以将背景颜色和前景颜色改为这样的颜色,但这会为所有文本着色当然:

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

你得到的结果:

enter image description here

答案 5 :(得分:0)

另一种选择。对于理论,请参阅其他答案。

这个使用预先配置的样式作为字段。注意暴露这些字段的时间,嗯,可变。

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) { }
    }
}

[编辑]更改回insertString而不是replaceSelection,因为后者在窗格不可编辑时失败

答案 6 :(得分:0)

另一种选择。对于理论,请参阅其他答案。

这个在添加文本时创建属性,而不是像在nIcE cOw的答案中那样派生样式。功能相同,因为窗格将属性与任何以前使用的属性合并。

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) { }
    }
}

[编辑]更改回insertString而不是replaceSelection,因为后者在窗格不可编辑时失败