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