How to Change the Color of Specific Words in a Jtextpane

How to change the color of specific words in a JTextPane?

Overwriting paintComponent will not help you.

This is not an easy one, but not impossible either. Something like this will help you:

DefaultStyledDocument document = new DefaultStyledDocument();
JTextPane textpane = new JTextPane(document);
StyleContext context = new StyleContext();
// build a style
Style style = context.addStyle("test", null);
// set some style properties
StyleConstants.setForeground(style, Color.BLUE);
// add some data to the document
document.insertString(0, "", style);

You may need to tweak this, but at least it shows you where to start.

Specify text color whenever I write a particular word in JTextPane

Here is a solution using a map of words to colors. As you can see, I mapped apple to red and the word green to the color green

public class Test {

HashMap<String, Color> myMap = new HashMap<String, Color>();

public static void main(String[] args) {
new Test();
}

public Test() {
myMap.put("apple", Color.RED);
myMap.put("apples", Color.RED);
myMap.put("green", Color.GREEN);
String text = "This is a green apple and I like to eat Apples";

JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();

Style style = textPane.addStyle("Red Style", null);
StyleConstants.setForeground(style, Color.red);
ArrayList<Chunk> chunks = getColorsBasedOnText(text, textPane);
try {
for (Chunk chunk : chunks) {
doc.insertString(doc.getLength(), chunk.text + " ", chunk.style);
}
} catch (BadLocationException e) {
}

JFrame frame = new JFrame("Test");
frame.getContentPane().add(textPane);
frame.pack();
frame.setVisible(true);
}

private ArrayList<Chunk> getColorsBasedOnText(String text, JTextPane textPane) {
ArrayList<Chunk> chunks = new ArrayList<Chunk>();
for (String word: text.split(" ")) {
Chunk chunk = new Chunk();
chunk.text = word;
Color color = myMap.get(word.toLowerCase());
if (color != null) {
chunk.style = textPane.addStyle("Style", null);
StyleConstants.setForeground(chunk.style, color);
}
chunks.add(chunk);
}
return chunks;
}

private class Chunk {
public String text;
public Style style;
}

Specific words don't change color in a JTextPane [java]

Almost you did it ok. Almost.
Small changes to your code required:

  1. add parameter for method initComponents:

    initComponents(DefaultStyledDocument doc)

  2. pass this parameter to constructor of JTextPane

    textModel = new javax.swing.JTextPane(doc);

  3. remove JTextPane txt = new JTextPane(doc); from NewJFrame constructor

  4. move initComponents to the end of the NewJFrame constructor

    initComponents(doc);

How to change text color in the JTextArea?

JTextArea is meant to entertain Plain Text. The settings applied to a single character applies to whole of the document in JTextArea. But with JTextPane or JEditorPane you have the choice, to colour your String Literals as per your liking. Here with the help of JTextPane, you can do it like this :

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

here is the Output :

JTextPane



Related Topics



Leave a reply



Submit