How to change the text color in a JTextPane?

3

I'm developing a chat and it uses JTextPane to display messages in different colors for each user. However, I'm not sure how I can change the text colors of this component.

Example:
We have two people (John and Peter), when I receive a message from Peter for the first time the chat chooses a color and then uses this color for all of John's messages, while giving another color to Peter's messages, but all of them appeared in the same JTextPane , users are identified by their IP address.

Something like this:

    
asked by anonymous 22.07.2016 / 21:41

4 answers

5

From a sample taken from this link , I've done an example where it's possible change the text at run time by using the StyleContext and AttributeSet . To use, simply adapt the ColorPane component in your code, and pass the desired color along with the text in the append method, depending on the user you are typing.

Follow the code:

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

public class ChangeColorPaneTest extends JFrame {

    JTextField field;
    ColorPane pane;
    boolean alternate = true;

    public void startFrame() {
        pane = new ColorPane();
        pane.setBackground(new Color(245, 245, 245));

        field = new JTextField();
        field.setPreferredSize(new Dimension(getSize().width, 25));
        field.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //action apenas para fins de exemplificação
                Color textColor = alternate ? Color.red : Color.BLUE;
                pane.append(textColor, field.getText());
                alternate = !alternate;
                field.setText("");
            }
        });

        JScrollPane scrollpane = new JScrollPane(pane);
        scrollpane.setPreferredSize(new Dimension(400, 200));
        setTitle("ColorPane example");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(scrollpane, BorderLayout.CENTER);
        add(field, BorderLayout.PAGE_END);
        field.requestFocusInWindow();
        pack();
        setVisible(true);
    }

    class ColorPane extends JTextPane {

        public void append(Color c, String s) {
            //implementação utilizando StyleContext
            StyleContext sc = StyleContext.getDefaultStyleContext();
            AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                    StyleConstants.Foreground, c);

            // tamanho do texto já no component
            int len = getDocument().getLength(); 
            // altera a posicao do cursor para o fim(se não houver seleção)
            setCaretPosition(len); 
            setCharacterAttributes(aset, false);
            //O \n é apenas para o texto ser quebrado
            //para fins de demonstracao
            //se não houver seleção, adiciona o texto no fim
            replaceSelection(s.concat("\n")); 
        }

    }

    public static void main(String argv[]) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                ChangeColorPaneTest pane = new ChangeColorPaneTest();
                pane.startFrame();
            }
        });
    }
}

Result:

Reference:

How to Use Panes and Text Panes

    
26.07.2016 / 16:18
0

If you only want to change the color of the text, do so:

textPane.setForeground(Color.RED);

And if it is to change the background color, do so:

textPane.setBackground(Color.BLACK);

And do not forget to import the class Color :

import java.awt.Color;
    
25.07.2016 / 17:21
-1

First you create the object so you can modify it

private jTextPane1 = new javax.swing.JTextPane();

then you can access it to modify in the following ways.

You may be putting it directly into the constructor for example:

    public NovoJFrame() {
      initComponents();
      //use setForeground para mudar a cor e Color pra colocar o código rgb da cor
      jTextPane1.setForeground(new Color(255,0,0));

}

or you can put it in some function like:

public mudaCor(){
//use setForeground para mudar a cor e Color pra colocar o código rgb da cor
  jTextPane1.setForeground(new Color(255,0,0));
}
    
22.07.2016 / 22:19
-1

Just as an alternative, if you learn, try using JavaFX. It is much simpler and much more dynamic, in it you would only use label1.setTextFill(Color.web("#0076a3")); , in fact it even has an editor called Scene Builder it does everything. Look what you give to create. It even gives to create games so perfect and does not occupy any space.

    
23.07.2016 / 07:21