Hightlight and change Color of Text in JTextArea
You can use JComponent#setForeground(Color) - But not on JTextArea
. It's not designed for that purpose. Instead, use a JEditorPane or JTextPane.
On these components you can also use HTML tags, like:
"<html>My text: <font color=\"blue\">" + myString + "</font></html>"
You can change the background of the JTextArea
using JTextArea#setBackground (If that what you mean).
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 :
Highlight Text In JTextArea In Presence of Duplicate Lines
You had it almost all by yourself there were few issues though.
- You should use
getSelectionStart()
rather thangetCaretPosition()
. - Highlight should start from
index
not fromindex-1
.
Please see the example below. Select what you want to highlight right click on the textArea or press the button to highlight your selection:
public class HighlightingTextArea {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JTextArea textArea = new JTextArea(10, 44);
textArea.append("AAAA\nBBBB\nAAAA\nCCCC\nDDDD\nAAAA");
JButton b = new JButton(new AbstractAction("highlight") {
@Override
public void actionPerformed(ActionEvent e) {
highlightTextAreaSelection(textArea);
}
});
textArea.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
if (e.getButton() == MouseEvent.BUTTON3) {
highlightTextAreaSelection(textArea);
}
}
});
JPanel panel = new JPanel(new BorderLayout());
panel.add(textArea);
panel.add(b, BorderLayout.SOUTH);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setVisible(true);
}
});
}
private static void highlightTextAreaSelection(JTextArea textArea) {
String highlightedText = textArea.getSelectedText();
if (highlightedText != null) {
try {
int index = textArea.getText().indexOf(highlightedText, textArea.getSelectionStart());
textArea.getHighlighter().addHighlight(index, index + highlightedText.length(),
new DefaultHighlighter.DefaultHighlightPainter(Color.ORANGE));
} catch (BadLocationException ex) {
}
}
}
}
JTextArea or JTextPane Set Highlighted Text Color
If you mean the "normal" highlight color (when you drag your mouse over the text), this can simply be achieved by
textArea.setSelectionColor(Color.LIGHT_GRAY);
(or whatever color you want it to have.)
If you want to programmatically highlight a character sequence in your text area:
String searchedWord = "word";
int pos1 = textArea.getText().indexOf(searchedWord);
int pos2 = pos1 + searchedWord.length();
try {
textArea.getHighlighter().addHighlight(pos1, pos2,
new DefaultHighlighter.DefaultHighlightPainter(Color.LIGHT_GRAY));
} catch (BadLocationException e) {
e.printStackTrace();
}
(The same works for a JTextPane
too)
Different text color in a JTextArea
Not with a JTextArea
. You can, however, use a JTextPane
which allows for attributes to be applied to text. If you want examples, take a look at the Text Component Tutorial.
Related Topics
Strange Behavior of Class.Getresource() and Classloader.Getresource() in Executable Jar
Why Is Constructor of Super Class Invoked When We Declare the Object of Sub Class? (Java)
Steganography in Lossy Compression (Java)
Copy Directory from a Jar File
Spring Boot Actuator Application Won't Start on Ubuntu Vps
Weird Java Behavior with Casts to Primitive Types
How to Use Google's Gson API to Deserialize JSON Properly
Information About _Java_Options
How to Mix --Class-Path and --Module-Path in Javac (Jdk 9)
Whats the Use of Saying <? Extends Someobject> Instead of <Someobject>
How to Add Close Button to a Jtabbedpane Tab
How to Extract Parameters from a Given Url
Org.Openqa.Selenium.Webdriverexception: Unknown Error: Call Function Result Missing 'Value'
How to Change the Color of Specific Words in a Jtextpane
Conversion from 12 Hours Time to 24 Hours Time in Java
Display Blob (Image) Through Jsp