Comment changer la couleur du texte dans la JtextArea?

j'ai besoin de savoir comment faire ceci:

disons: j'ai un code dans la jtextArea comme ceci,

LOAD R1, 1 DEC R1 Magasin M, R1 Ajouter R4, R1, 8

je voulais changer la couleur de la charge, DEC, stocker et ajouter à la couleur bleue R1, R4 à couleur verte M à rouge nombres à ORANGE

Comment changer la couleur de ce texte? Ces textes proviennent de notepad ou peuvent être tapés directement dans le textArea.

je vous Remercie à l'avance.

27
demandé sur mKorbel 2012-03-11 03:11:33

7 réponses

JTextArea est destiné à divertir Plain Text. Les réglages appliqués à un caractère unique s'applique à l'ensemble du document JTextArea. Mais avec JTextPane ou JEditorPane vous avez le choix, de colorer votre String Literals selon votre goût. Ici, avec l'aide de JTextPane, vous pouvez le faire comme ceci :

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

voici la sortie:

JTextPane

73
répondu nIcE cOw 2013-03-09 17:24:54

car il est possible d'utiliser Highlighter (ou Html) pour JTextArea, cette API implémentant des options réduites pour le texte stylisé

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

par rapport à JTextPane il y a des options plus variables, par exemple Highlighter, avec Html ou sans Html, Font, ou mettez un autre JComponent à l'intérieur en utilisant Html ou directement (sachez JTextArea aussi, mais...)

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();
            }
        });
    }
}
20
répondu mKorbel 2012-03-11 00:29:08

L'utilisation peut soit utiliser un JEditorPane avec HTML ou écrire un Document personnalisé qui colore des éléments.

3
répondu Scott Faria 2012-03-10 23:35:22

vous ne pouvez pas avoir des caractères différents dans des couleurs différentes dans une JTextArea (du moins pas sans quelques hackery complexes). Utilisez un JTextPane ou un JEditorPane à la place. Ensuite, vous pouvez accéder à son StyledDocument:

StyledDocument sdoc = pane.getStyledDocument()

EDITED: modifié en appelant directement getStyledDocument, au lieu de lancer le résultat de getDocument ()

Appel setCharacterAttributes sur le StyledDocument pour changer les couleurs des différents caractères ou substrats.

2
répondu Gigatron 2012-03-18 00:42:39

pour certaines couleurs de base (la seule chose que vous pouvez faire avec JTextArea) vous pouvez changer les couleurs de fond et de premier plan à quelque chose comme ceci, mais cela va colorer tout le texte bien sûr:

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

Le résultat:

enter image description here

1
répondu Rok T. 2017-08-25 13:01:58

Juste une autre alternative. Pour la théorie, voir les autres réponses.

celui-ci crée des attributs lors de l'ajout de texte, au lieu de dériver le style comme dans la réponse de nIcE cOw. La fonctionnalité est la même, car le volet va fusionner les attributs avec tous les attributs précédemment utilisés.

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] retour à insertString au lieu de replaceSelection parce que cette dernière échoue lorsque la vitre n'est pas modifiable

0
répondu Mark Jeronimus 2018-06-12 09:26:57

Juste une autre alternative. Pour la théorie, voir les autres réponses.

celui-ci utilise des styles préconfigurés comme champs. Attention en exposant ces champs comme ils sont, 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] retour à insertString au lieu de replaceSelection parce que cette dernière échoue lorsque la vitre n'est pas modifiable

0
répondu Mark Jeronimus 2018-06-12 09:27:10