To display the text in different colors in JTextField

I need to display the text in text field in different colors. When
my cursor is within the flower brackets i have to enter the string so
that it will come in some color, say blue. When my cursor is out of the
flower brackets It will display those text in different color, say red.
So can any one please give me an idea to do that. Iam using Swings
to design the GUI. Urgent need.Waiting for your reply.
[428 byte] By [manyam537] at [2007-11-19 11:02:46]
# 1 Re: To display the text in different colors in JTextField
you can use JTextPane object instead of JTextField. You can get necessary behaviour by the working with Style's objects.
bolshik at 2007-11-10 2:23:10 >
# 2 Re: To display the text in different colors in JTextField
JTextField supports html text so u can write html content on mouse move

i.e jTextFieldObj.setText("<html><font color=red>"+yourText+"</font></html>");
vishrank at 2007-11-10 2:24:10 >
# 3 Re: To display the text in different colors in JTextField
THis is my code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.text.BadLocationException;
public class SwingTest extends JFrame{
private JTextField text;
private Font textFont;

SwingTest(String title){
setTitle(title);
setBounds( 10, 10, 300, 200);
textFont = new Font("Verdana",Font.BOLD,14);
text = new JTextField(20);
text.setFont(textFont);
text.setForeground(Color.blue);
text.addKeyListener( new FieldsKeyListener());
JPanel p = new JPanel();
p.add(text);
getContentPane().add(p);

}
class FieldsKeyListener extends KeyAdapter
{

public void keyReleased(KeyEvent evt){
String setValue = null;
String str = null;
String str1 = text.getText();
int i = text.getCaretPosition();
int j = 0;
if(i >= 3) {

try {

str = text.getText(i-3,3);
}
catch(BadLocationException be)
{
System.out.println("The bad location expression is"+be);
}

if((str.equals("/ID")) || (str.equals("/id")) || (str.equals("/TI")) || (str.equals("/ti")) ||
(str.equals("/IV")) || (str.equals("/iv")) || (str.equals("/CO")) || (str.equals("/co")) ||
(str.equals("/AB")) || (str.equals("/ab")) || (str.equals("/DE")) || (str.equals("/de")) ||
(str.equals("/CL")) || (str.equals("/cl")) || (str.equals("/PU")) || (str.equals("/pu")) ||
(str.equals("/PR")) || (str.equals("/pr")) || (str.equals("/IP")) || (str.equals("/ip")) ||
(str.equals("/WD")) || (str.equals("/wd")) || (str.equals("/FT")) || (str.equals("/ft"))){
setValue = "()";
str = str1+""+setValue+"";
text.setText(str);
j = text.getCaretPosition();
text.setCaretPosition(j-1);
}

}
}
}
public static void main(String[] args){
SwingTest test = new SwingTest("Swing Test");

test.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){System.exit(0);}
});
test.setVisible(true);
}
}

Now what i want to do is, whwnever i enter some thing within the flower brackets, i have to get that or show that text in different color.
manyam537 at 2007-11-10 2:25:07 >
# 4 Re: To display the text in different colors in JTextField
vishrank, could you give an example about using html attributes at the JTextField object?
This code shows all of the tags as the simple text:

...
JPanel panel = new JPanel();
JTextField textField1 = new JTextField();
JTextField textField2 = new JTextField();
String text = "<html><font color=\"blue\">wer";
textField1.setText("<html><font color=\"blue\">" + "asdfds" + "</font></html>");
textField2.setText(text);
JLabel label = new JLabel(text);
panel.add(textField1);
panel.add(textField2);
panel.add(label);
frame.getContentPane().add(panel);
...
bolshik at 2007-11-10 2:26:13 >
# 5 Re: To display the text in different colors in JTextField
Hello Bolshik,

Can you please give me an idea how to display the text within the flower brackets in different color. I posted the code before. If you know how to do, please let me know. Its very much needed for me.
manyam537 at 2007-11-10 2:27:10 >
# 6 Re: To display the text in different colors in JTextField
you may use JTextPane component and use different styles to highlight necessary text.
bolshik at 2007-11-10 2:28:10 >
# 7 Re: To display the text in different colors in JTextField
HI Bolshik,

Can you please give sample code to display text in different colors in JTextPane using Styles object. Text is enterd i.e text is not static. We have to capture the sting in flower brackets. Iam not able to that. So that's the reason i can't able to apply Styles. So please see my code and help me regarding this problem.
manyam537 at 2007-11-10 2:29:13 >
# 8 Re: To display the text in different colors in JTextField
simple example:

import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.Document;
import javax.swing.text.BadLocationException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
* User: denis Date: 13.07.2005 Time: 10:53:41
*/
public class A {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();

final JTextPane textPane = new JTextPane();
textPane.setPreferredSize(new Dimension(400, 25));
final Document doc = textPane.getDocument();

/* Styles */
final Style normal = textPane.addStyle("Normal", null);
final Style brackets = textPane.addStyle("Brackets", null);
StyleConstants.setForeground(normal, Color.BLACK);
StyleConstants.setForeground(brackets, Color.BLUE);
textPane.setText("abc");

textPane.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
int currentCaretPosition = textPane.getCaretPosition();

if ((e.getKeyChar() == KeyEvent.VK_BACK_SPACE) || (e.getKeyChar() == KeyEvent.VK_DELETE)
|| (e.getKeyChar() == KeyEvent.VK_ENTER)) {
return;
}

try {
if (0 != currentCaretPosition) {
if (isCaretInBracket(textPane)) {
doc.insertString(textPane.getCaretPosition(), String.valueOf(e.getKeyChar()), brackets);
} else if ("id".equals(doc.getText(currentCaretPosition - 1, 1) + e.getKeyChar())) {
doc.insertString(currentCaretPosition, String.valueOf(e.getKeyChar()) + "()", normal);
textPane.setCaretPosition(currentCaretPosition + 2);
} else {
doc.insertString(textPane.getCaretPosition(), String.valueOf(e.getKeyChar()), normal);
}
} else {
doc.insertString(textPane.getCaretPosition(), String.valueOf(e.getKeyChar()), normal);
}
e.consume();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});

JPanel panel = new JPanel();
panel.add(textPane);

contentPane.add(panel);
frame.show();
}

private static boolean isCaretInBracket(JTextPane textPane) {
String text = textPane.getText();
int fromIndex = 0;
while (-1 != text.indexOf('(', fromIndex)) {
int bracketStartIndex = text.indexOf('(', fromIndex);

if (textPane.getCaretPosition() > bracketStartIndex) {
if (bracketStartIndex == text.length() - 1) {
return true;
} else if (-1 == text.indexOf(')', bracketStartIndex + 1)) {
return true;
} else if (textPane.getCaretPosition() <= text.indexOf(')', bracketStartIndex + 1)) {
return true;
}
}

fromIndex = bracketStartIndex + 1;
}
return false;
}
}

You should also operate situation when user enters '(' or ')' inside the brackets and repaint the whole text.
bolshik at 2007-11-10 2:30:15 >
# 9 Re: To display the text in different colors in JTextField
complete version of the required class:

package customhighlight;

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

/**
* Class extends <code>JTextPane</code> and provides the capability to automatically generate brackets after defined
* templates and highlight the text inside them with the custom color.
*
* @author Denis Zhdanov
* @version 1.0
*/
public class HighlightedTextPane extends JTextPane {

/* Templates for the brackets generating */
private String[] templates;

/* Styles */
private Style normalStyle;
private Style highlightedStyle;

/* Styles colors */
private Color normalColor = Color.BLACK;
private Color highlightColor = Color.BLUE;

/**
* Creates a <code>HighlightedTextPane</code> with the specified set of templates and default colors -- black as the
* color of the normal text and blue as the color of the highlighted text.
*
* @param templates the set of templates to be processed
* @throws EmptyTemplateException if no template has been defined
*/
public HighlightedTextPane(String[] templates) throws EmptyTemplateException {
super();

/* Templates iniatilization */
if (0 == templates.length) {
throw new EmptyTemplateException();
}
this.templates = templates;

/* Styles initialization */
this.normalStyle = this.addStyle("Normal", null);
this.highlightedStyle = this.addStyle("Highlight", null);
StyleConstants.setForeground(normalStyle, normalColor);
StyleConstants.setForeground(highlightedStyle, highlightColor);

this.addKeyListener(new HighlightProcessor());
}

/**
* Creates a <code>HighlightedTextPane</code> with the specified set of templates and colors of the normal and
* highlighted text.
*
* @param templates the set of templates to be processed
* @param normalColor color of the normal text
* @param highlightColor color of the highlighted text
* @throws EmptyTemplateException if no template has been defined
*/
public HighlightedTextPane(String[] templates, Color normalColor, Color highlightColor)
throws EmptyTemplateException {
super();

/* Templates iniatilization */
if (0 == templates.length) {
throw new EmptyTemplateException();
}
this.templates = templates;

/* Styles initialization */
this.normalStyle = this.addStyle("Normal", null);
this.highlightedStyle = this.addStyle("Highlight", null);
StyleConstants.setForeground(normalStyle, normalColor);
StyleConstants.setForeground(highlightedStyle, highlightColor);

this.addKeyListener(new HighlightProcessor());
}

private class HighlightProcessor extends KeyAdapter {

public void keyTyped(KeyEvent e) {
if ((e.getKeyChar() == KeyEvent.VK_BACK_SPACE) || (e.getKeyChar() == KeyEvent.VK_DELETE)
|| (e.getKeyChar() == KeyEvent.VK_ENTER)) {
HighlightedTextPane.this.repaintText();
return;
}

int currentPosition = HighlightedTextPane.this.getCaretPosition();
Document doc = HighlightedTextPane.this.getDocument();
boolean isInserted = false;
try {
for (int i = 0; i < templates.length; i++) {
if (doc.getLength() < (templates[i].length() - 1)) {
continue;
}

if (templates[i].equals(doc.getText(currentPosition - templates[i].length() + 1, templates[i].length() - 1) + e.getKeyChar())) {
doc.insertString(currentPosition, String.valueOf(e.getKeyChar()) + "()", normalStyle);
HighlightedTextPane.this.setCaretPosition(currentPosition + 2);
isInserted = true;
break;
}
}

if (!isInserted) {
doc.insertString(currentPosition, String.valueOf(e.getKeyChar()), normalStyle);
}
e.consume();
HighlightedTextPane.this.repaintText();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}

private void repaintText() {
Document newDoc = new DefaultStyledDocument();
String text = this.getText();

int caretPosition = this.getCaretPosition();
int fromIndex = 0;

try {
while (0 != text.length()) {
int currentStartBracketIndex = this.getStartBracketIndex(text, fromIndex);

/* Checking that opening bracket exists */
if (-1 != currentStartBracketIndex) {
int currentEndBracketIndex = this.getEndBracketIndex(text, currentStartBracketIndex);
/* Checking the closing bracket exists */
if (-1 != currentEndBracketIndex) {
int nearestOpeningBracket = this.getNearestOpeningBracket(text, currentEndBracketIndex);

if (-1 != nearestOpeningBracket) {
newDoc.insertString(newDoc.getLength(), text.substring(0, nearestOpeningBracket), this.normalStyle);
newDoc.insertString(newDoc.getLength(), text.substring(nearestOpeningBracket, currentEndBracketIndex + 1), this.highlightedStyle);
} else {
newDoc.insertString(newDoc.getLength(), text.substring(0, currentEndBracketIndex + 1), this.normalStyle);
}

if (text.length() != currentEndBracketIndex + 1) {
text = text.substring(currentEndBracketIndex + 1);
} else {
text = "";
}
}
/* If no opening brackets has been found, repainting opening
* bracket and following text with the highlighted color
*/
else {
newDoc.insertString(newDoc.getLength(), text.substring(0, currentStartBracketIndex), this.normalStyle);
newDoc.insertString(currentStartBracketIndex, text.substring(currentStartBracketIndex), this.highlightedStyle);
text = "";
}
}
/* If no opening brackets has been found, repainting text
* with the normal color
*/
else {
newDoc.insertString(newDoc.getLength(), text, this.normalStyle);
text = "";
}
}
} catch (BadLocationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
this.setDocument(newDoc);
this.setCaretPosition(caretPosition);
}

private int getStartBracketIndex(String text, int fromIndex) {
return text.indexOf('(', fromIndex);
}

private int getEndBracketIndex(String text, int fromIndex) {
return text.indexOf(')', fromIndex);
}

private int getNearestOpeningBracket(String text, int closingBracketIndex) {
assert closingBracketIndex > 0 : "closingBracketIndex is less than zero";
boolean notFound = false;
int fromIndex = 0;
int result = -1;
while (!notFound) {
if ((text.indexOf('(', fromIndex) > closingBracketIndex) || (-1 == text.indexOf('(', fromIndex))) {
notFound = true;
} else {
result = text.indexOf('(', fromIndex);
fromIndex = result + 1;
}
}
return result;
}

private boolean isCaretInBracket() {
String text = this.getText();
int fromIndex = 0;
while (-1 != text.indexOf('(', fromIndex)) {
int bracketStartIndex = text.indexOf('(', fromIndex);

if (this.getCaretPosition() > bracketStartIndex) {
if (bracketStartIndex == text.length() - 1) {
return true;
} else if (-1 == text.indexOf(')', bracketStartIndex + 1)) {
return true;
} else if (this.getCaretPosition() <= text.indexOf(')', bracketStartIndex + 1)) {
return true;
}
}
fromIndex = bracketStartIndex + 1;
}
return false;
}

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();

HighlightedTextPane textPane = new HighlightedTextPane(new String[]{"id", "name"});
textPane.setPreferredSize(new Dimension(400, 25));

JPanel panel = new JPanel();
panel.add(textPane);

contentPane.add(panel);
frame.show();
}
}
bolshik at 2007-11-10 2:31:18 >
# 10 Re: To display the text in different colors in JTextField
and new class of the exception:

package customhighlight;

/**
* Thrown to indicate that an empty array of templates has been accessed.
*
* @author Denis Zhdanov
* @version 1.0
*/
public class EmptyTemplateException extends RuntimeException {

/**
* Constructs an <code>EmptyTemplateException</code> with no
* detail message.
*/
public EmptyTemplateException() {
super();
}

/**
* Constructs an <code>EmptyTemplateException</code> class
* with the specified detail message.
*
* @param text the detail message.
*/
public EmptyTemplateException(String text) {
super(text);
}

}
bolshik at 2007-11-10 2:32:11 >