How to change the color of the text in a Jtextpane?

Asked

Viewed 1,482 times

3

I’m developing a chat and he uses a JTextPane to display messages in different colors for each user. However, I don’t know how to change the colors of the text 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 will use this color for all of John’s messages, while giving another color to Peter’s messages, but they all appeared in the same JTextPane, users are identified by their IP address.

Something like this:

imagem demonstrando o efeito desejado

  • 2

    What have you tried to do? Add to the question what you have done so far.

4 answers

5


From a taken example of this link, made an example where it is possible to change the text at runtime, using the classes StyleContext and AttributeSet. To use, simply adapt the component ColorPane in your code, and pass the desired color along with the text in the method append, as the user who is typing.

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

Upshot:

gif animado com demonstração do código

Reference:

How to Use Editor Panes and Text Panes(Documentation)

1

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

textPane.setForeground(Color.RED);

And if you want to change the background color (background), do so:

textPane.setBackground(Color.BLACK);

And don’t forget to import the class Color:

import java.awt.Color;
  • 1

    This changes the whole font, and if you read the question carefully, you will see that it wants to change line pro line. This solution will not do it.

-1

First of all you create the object to be able to modify it

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

then you can access it to modify the following ways.

You might be putting right 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 for example:

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));
}
  • If what he wants is to switch the color of the text to each message, it will not work.

  • 1

    I wanted to use the style functions of this class. Do not apply to all text...

  • Change the color in the Jlabel object that will be inserted in Jpane and not directly in Jpane

  • Your answer is not explain this. If a question has been asked, it is because the OP has no notion of how to do this.

-1

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

a busy cat

  • 4

    The question is about swing and you answer with javafx?

  • 1

    From the java 9 swing will be removed, don’t you think it is better to already go learning Javafx that will replace it? Item 6 is expected in the next java . http://www.oracle.com/technetwork/javafx/overview/faq-1446554.html#6

  • @diegofm At first, I thought the same thing you did. But considering that the (a) AP is at the beginning of the project, I think this answer came in handy yes, especially because it’s not just a link, but it shows the line of code used to solve the problem. It is not much different from the classic "Use Jodatime" in the time-related answers in Java.

  • 3

    @Pabloalmeida if so, every swing question then will start to answer with javafx. The OP does not ask for alternatives in other technologies, it asks for help in relation to a component. This could be a comment, after all, the answer field is for suggestions that solve the problem, I do not know if having the OP learn another technology is a solution.

  • @diegofm In general, I agree with you, but every rule has an exception. In this specific case, for the reasons cited -- imminent replacement of Swing as an official GUI framework and the fact that the impact in changing technology at this stage is minimal -- I thought it was a good one, yes. Of course, the answer could be better worded, but I did not recommend exclusion for that reason. But I understand perfectly if you think differently-- I spent a long time "on the fence" in the analysis.

  • Another thing, the answer suggests another technology, but it doesn’t teach you how to solve the problem in another technology. Each one has his or her own judgement for seeing you, yet I do not see this as a valid answer, since it does not solve the problem of the question, since the purpose of the answer would be this.

  • That line of code in the answer ( label1.setTextFill(Color.web("#0076a3"));) does not do what the author(a) (a) of the answer said it does? If not, the answer is factually wrong, but there is another problem.

  • setTextFill does exactly what it asks, it’s not only for the Label, it serves also for Textarea and Textfield as it wants to change color to each message sent, just it change the HTML code of each message, it could be more complete as Pablo said the code already ready with the change. But I think the Author has already left, he has not even spoken if it is of interest to him, he has already succeeded and the diegofm fighting to see if you take my answer. Truth I don’t even waste my time helping others. https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/text-settings.htm

  • 2

    I’m not fighting to get your answer, I just didn’t agree that just having the OP learn another technology is a good solution. The site is made by the community, and this is called "debate". I respect the opinion of the other members and the community that decided to keep their response, but mine remains the same. It is important to provide a solution to the real problem faced in the question as well as suggest a technology migration as you did. The answer is not bad, only incomplete.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.