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:
add parameter for method
initComponents
:initComponents(DefaultStyledDocument doc)
pass this parameter to constructor of
JTextPane
textModel = new javax.swing.JTextPane(doc);
remove
JTextPane txt = new JTextPane(doc);
fromNewJFrame
constructormove initComponents to the end of the
NewJFrame
constructorinitComponents(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 :
Related Topics
How to Run MySQL In-Memory for Junit Test Cases
How Does Bitshifting Work in Java
Using Spring Resttemplate in Generic Method with Generic Parameter
Efficiently Finding the Intersection of a Variable Number of Sets of Strings
How Are Servlet Url Mappings in Web.Xml Used
Why Is Constructor of Super Class Invoked When We Declare the Object of Sub Class? (Java)
Programmatically Import Ca Trust Cert into Existing Keystore File Without Using Keytool
Accessing Resource Files from External Modules
How to Clear Permgen Space Error in Tomcat
How to Create a Delay in Swing
Dynamic Generic Typing in Java
Using PDFbox to Write Utf-8 Encoded Strings to a PDF
Spring Scheduling Task - Run Only Once