2012-03-10 33 views
25

necesito saber cómo hacer esto:¿Cómo cambiar el color del texto en JtextArea?

Digamos: Tengo un código en el JTextArea como este,

CARGA R1, 1 diciembre R1 TIENDA M, R1 ADD R4, R1, 8

quería cambiar el color de CARGA, DEC, el almacén y agregar a azul R1, R4 para dar color verde a rojo M números para ORANGE

Cómo cambiar t el color de este texto? Estos textos provienen del bloc de notas o se pueden escribir directamente en el área de texto.

Gracias de antemano.

+1

Mejor probablemente no utilizar un JTextArea pero en lugar de utilizar un JEditorPane o similar. –

+1

uso correcto [JTextComponent que admite texto estilizado] (http://docs.oracle.com/javase/tutorial/uiswing/components/editorpane.html), JTextArea no es el camino correcto para hacerlo ... – mKorbel

Respuesta

70

JTextArea está destinado a entretener a Plain Text. La configuración aplicada a un solo carácter se aplica a todo el documento en JTextArea. Pero con JTextPane o JEditorPane tiene la opción, para colorear su String Literals según lo desee.Aquí, con la ayuda de JTextPane, puede hacerlo de esta manera:

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

Aquí está la salida:

JTextPane

+0

gracias por la respuesta. ,, pero las palabras son dinámicas señor.?., No es estático. – Celine

+0

@Celine: Su bienvenida y me alegro de que lo haya ayudado de alguna manera. Bueno, entonces simplemente tiene que pasar sus palabras una por una a esta función, este es solo un pequeño ejemplo de programa. Tienes que encontrar la lógica para suministrar palabras de acuerdo a tus necesidades :-) –

+0

¿Cómo cambiaste el color del JFrame de azul a verde? – vijay

3

El uso puede usar un JEditorPane con HTML o escribir un documento personalizado que coloree los elementos.

2

No puede tener diferentes caracteres en diferentes colores en un JTextArea (al menos no sin algunos complejos hackers). Use un JTextPane o JEditorPane en su lugar. A continuación, puede acceder a su StyledDocument:

StyledDocument sdoc = pane.getStyledDocument() 

EDITADO: cambiado a llamar directamente getStyledDocument, en lugar de emitir el resultado de getDocument()

llamada setCharacterAttributes en el StyledDocument para cambiar los colores de individuo Caracteres o subcadenas.

20

ya que es posible el uso Highlighter (o HTML) para JTextArea, esta API en marcha opciones para el texto reduce stylled

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

en comparación con JTextPane hay opciones más variables, por ejemplo, Marcador, con o sin HTML HTML, fuentes, o dicho de otra JComponent el interior mediante HTML o directamente (JTextArea sabe también, pero ...)

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

¿Es posible también cambiar el color del texto y no solo BG? –

+0

@Lennart Rolland solo un color para JTextArea, para JTextPane es posible establecer fore & background – mKorbel

0

Por alguna coloración básica (la única cosa que puede hacer con JTextArea) se puede cambiar los colores de fondo y primer plano a algo como esto, pero esto va a colorear todo el texto, por supuesto:

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

El resultado que se obtiene:

enter image description here

Cuestiones relacionadas