Skip to main content

help with text coloring in JTextPane

1 reply [Last post]
spiderwick
Offline
Joined: 2007-08-12
Points: 0

hi. i'm trying to make a code interpreter that should change font colors of selected syntax. I've seen a post from seane and i'm trying it with my UI to see if the same logic would be good for my UI but there seems to be some problem, its too slow and the changing if colors doesn't apply. Does anybody know why?

Here's the 5 part code with main in Parser.java:

[code]

import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;
import java.util.*;
import javax.swing.text.*;
import javax.swing.event.*;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.File;

public class Parser
{
public static void main(String[] args)
{
try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
catch (Exception e) {;}
Parser_Model model = new Parser_Model();
Parser_View view = new Parser_View("Sparrow Programming Language");
Parser_Controller controller = new Parser_Controller(model,view);
}
}

class Parser_Model
{
String curDir;
String sourceName="";
String reportName = "File.txt";
File sourceFile=new File (sourceName);
File reportFile=new File (reportName);
JFileChooser fileChooser = new JFileChooser();

Parser_Model model; Parser_View view;
public String run(String s)
{
return s.toUpperCase();
}

public void exit()
{
System.exit(0);
}

public void open()
{
//FilePicker open = new FilePicker();
JFileChooser chooser = new JFileChooser(curDir);
chooser.setMultiSelectionEnabled(true);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

String[] rjq = new String[] {"rjq"};
chooser.addChoosableFileFilter(new ExtFilter(rjq,
"RJQ file (*.rjq)"));
int option = chooser.showOpenDialog(view);

if (option==JFileChooser.APPROVE_OPTION)
{

try {
sourceFile = chooser.getSelectedFile();
java.net.URL url = sourceFile.toURL();
view.getSourceArea().setPage(url);

} catch (Exception e) {
view.getSourceArea().setText("Error!: " + e);
}
}
}

public void save()
{
if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(view)) {
reportName = fileChooser.getSelectedFile().getPath();
try
{
FileWriter out = new FileWriter(reportName);
String text = view.getSourceArea().getText();
out.write(text);
out.close();
}
catch (IOException e) {view.getSourceArea().setText("Error!: " + e);}
}
}
}

class Parser_View extends JFrame // provides GUI
{
private final Color SKYBLUE = new Color(230, 230, 250);

//declare button components
private JButton runButton = new JButton("Run");
private JButton clrButton = new JButton("Clear Source");
private JButton clr2Button = new JButton("Clear Output");
private JButton openButton = new JButton ("Open File");
private JButton saveButton = new JButton("Save File");
private JButton exitButton = new JButton("Exit");

//declare file area components
private static NewEditPane sourceArea = new NewEditPane();

//private static JTextPane sourceArea = new JTextPane();
private static JTextPane reportArea = new JTextPane();

//build the layers of panels needed
JPanel buttons = new JPanel(new GridLayout(6,1,2,2));
JScrollPane sourcePane = new JScrollPane(sourceArea);
JScrollPane reportPane = new JScrollPane(reportArea);
JPanel sPanel = new JPanel(); JPanel rPanel = new JPanel();
JPanel fileZone = new JPanel(new GridLayout(2,1,2,2));

//main is split into 2 grid regions
JPanel main = new JPanel(new BorderLayout());

public Parser_View(String title) // the gui constructor
{ //start with framework
super(title);
setBounds(10,10,750,500);
setResizable(false);
//setDefaultCloseOperation(System.Exit);
// sourceArea.Start();
//construct files/io zone
sourceArea.setBackground(Color.white);
reportArea.setEditable(false);
reportArea.setBackground(Color.white);

sourceArea.setPreferredSize(new Dimension(400,150));
reportArea.setPreferredSize(new Dimension(400,150));

sPanel.add(sourcePane);
sPanel.setBackground(SKYBLUE);
sPanel.setBorder(new TitledBorder("Source"));

rPanel.add(reportPane);
rPanel.setBackground(SKYBLUE);
rPanel.setBorder(new TitledBorder("Output"));

fileZone.add(sPanel);
fileZone.add(rPanel);
fileZone.setBackground(SKYBLUE);
fileZone.setBorder(new TitledBorder("Source/Output"));

//construct controls zone
buttons.add(runButton);
buttons.add(saveButton);
buttons.add(openButton);
buttons.add(clrButton);
buttons.add(clr2Button);
buttons.add(exitButton);

buttons.setBackground(SKYBLUE);
buttons.setBorder(new TitledBorder("Menu"));

//complete the panel assembly
main.add("Center",fileZone);
main.add("East",buttons);
this.getContentPane().add("Center",main);
setFocus();
setVisible(true);
}

private String terminal = "MAIN";

//view object field accessors
public static NewEditPane getSourceArea()
{
return sourceArea;
}

public String getReportArea()
{
return reportArea.getText();
}

public void setSourceArea(String g)
{
sourceArea.setText(g);
}

public void setReportArea(String g)
{
reportArea.setText(g);
}

public void setFocus()
{
sourceArea.requestFocus();
}

//view object helper methods
public void isNullWS()
{
boolean flag = true;
if (sourceArea.getText().length() == 0) {flag=false;}

//openButton.setEnabled(flag);
flag = true; if (reportArea.getText().length() == 0) {flag=false;}
//clr2Button.setEnabled(flag);
}
public void screenKeyListener(KeyListener kl)
{
sourceArea.addKeyListener(kl);
}
public void buttonActionListeners(ActionListener al)
{
runButton.addActionListener(al);runButton.setActionCommand("run");
clrButton.addActionListener(al);clrButton.setActionCommand("clr");
clr2Button.addActionListener(al);clr2Button.setActionCommand("clr2");
openButton.addActionListener(al);openButton.setActionCommand("open");
saveButton.addActionListener(al);saveButton.setActionCommand("save");
exitButton.addActionListener(al);exitButton.setActionCommand("exit");
}
}

class Parser_Controller implements ActionListener, KeyListener
{
private String sText, rText;
Parser_Model model; Parser_View view;

public Parser_Controller(Parser_Model model, Parser_View view)
{
this.model = model; this.view = view;
// Give the model a start situation as per what the GUI will show.
view.isNullWS();
// Add listeners from this class to the buttons of the view.
view.buttonActionListeners(this);
view.screenKeyListener(this);
}
// methods to deal with the interactions performed on the View.
public void actionPerformed(ActionEvent ae)
{
String action_com = ae.getActionCommand();
if (action_com.equals("run"))
{
sText=view.getSourceArea().getText();
rText=model.run(sText);
view.setReportArea(rText);view.isNullWS();
}
else if (action_com.equals("clr"))
{
view.setSourceArea("");view.isNullWS();
}
else if (action_com.equals("clr2"))
{
view.setReportArea("");view.isNullWS();
}
else if (action_com.equals("exit"))
{
model.exit();
}

else if (action_com.equals("open"))
{
model.open();
}

else if (action_com.equals("save"))
{
model.save();
}

view.setFocus(); // keep cursor in source area
}

public void keyReleased(KeyEvent event){}//view.isNullWS();}
public void keyTyped(KeyEvent event){}
public void keyPressed(KeyEvent event){}

}

import javax.swing.text.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;

public class EditUtil{

public static void setAttribute(StyledDocument doc, Style style, int start, int len){
if(len<=0)
return;
doc.setCharacterAttributes (start, len, style, false);
}

public static Style createStyle(JTextPane textPane, Color color, String name){
Style style = textPane.addStyle(name, null);
StyleConstants.setForeground(style, color);
return style;
}

public static boolean isOperator(char c){
boolean b = false;
switch(c){
case '+':
case '-':
case '*':
case '/':
case '&':
case '|':
case '^':
case '%':
case '!':
case '=':
case '>':
case '<':
b = true;
break;
default:
break;
}
return b;
}

public static boolean isPrimitive(HashMap primitiveTypes, String str){
if(primitiveTypes.get(str) == null)
return false;
return true;
}

public static boolean isKeyword(HashMap keywords, String str){
if(keywords.get(str) == null)
return false;
return true;
}

public static String getAttributeAt(StyledDocument doc, int index){
AttributeSet s = doc.getCharacterElement(index).getAttributes();
return (String)s.getAttribute(StyleConstants.NameAttribute);
}

public static int getEndOfLine(char[] chars, int index){
int len = chars.length;
for(int i = index; i0 ; i--)
if(chars[i] == '\n' || chars[i]=='\r')
return i+1;
return 0;
}

}

import java.util.HashMap;
public class JavaKeywords{

private static HashMap keywords = new HashMap();
private static HashMap primitiveTypes = new HashMap();
private static boolean isKeywordSet = false;
private static boolean isPrimitiveTypeSet = false;

public static HashMap getKeyWords(){
if(!isKeywordSet)
setKeywords();
return keywords;
}

public static HashMap getPrimitiveTypes(){
if(!isPrimitiveTypeSet)
setPrimitiveTypes();
return primitiveTypes;
}

private static void setKeywords(){
keywords.put("new", "new");
keywords.put("null", "null");
keywords.put("public", "public");
keywords.put("private", "private");
keywords.put("protected", "protected");
keywords.put("static", "static");
keywords.put("final", "final");
keywords.put("finally", "finally");
keywords.put("void", "void");
keywords.put("switch", "switch");
keywords.put("case", "case");
keywords.put("default", "default");
keywords.put("class", "class");
keywords.put("interface", "interface");
keywords.put("abstract", "abstract");
keywords.put("implements", "implements");
keywords.put("extends", "extends");
keywords.put("import", "import");
keywords.put("try", "try");
keywords.put("catch", "catch");
keywords.put("throws", "throws");
keywords.put("throw", "throw");
keywords.put("break", "break");
keywords.put("for", "for");
keywords.put("while", "while");
keywords.put("do", "do");
keywords.put("return", "return");
keywords.put("if", "if");
keywords.put("else", "else");
keywords.put("instanceof", "instanceof");
keywords.put("package", "package");
keywords.put("transient", "transient");
keywords.put("synchronized", "synchronized");
keywords.put("this", "this");
keywords.put("super", "super");
isKeywordSet = true;
}

private static void setPrimitiveTypes(){
primitiveTypes.put("int", "int");
primitiveTypes.put("double", "double");
primitiveTypes.put("float", "float");
primitiveTypes.put("long", "long");
primitiveTypes.put("char", "char");
primitiveTypes.put("byte", "byte");
primitiveTypes.put("short", "short");
primitiveTypes.put("boolean", "boolean");
primitiveTypes.put("true", "true");
primitiveTypes.put("false", "false");
primitiveTypes.put("String", "String");
isPrimitiveTypeSet = true;
}

}

import javax.swing.text.StyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.Style;
import javax.swing.JTextPane;
import java.util.HashMap;
import java.awt.Color;

public class NewJavaUtil{

private JTextPane textPane;
private static HashMap keywords = null;
private static HashMap primitiveTypes = null;
private static Style styleWord,styleKeyword,styleNumber,styleOperator,styleBracket,styleString,styleComment,
stylePrimitive,styleLineComment;
private int currLen = 0;
private StringBuffer sb;
private int cur = 0;
private boolean isNumber = false;
private Style lastSelectedAttribute;

public NewJavaUtil(JTextPane textPane){
this.textPane = textPane;
setStyles();
keywords = JavaKeywords.getKeyWords();
primitiveTypes = JavaKeywords.getPrimitiveTypes();
}

private void setStyles(){
Color c = new Color(-16777012);
Color c1 = new Color(51,51,51);
styleWord = EditUtil.createStyle(textPane, textPane.getForeground(),"word");
styleKeyword = EditUtil.createStyle(textPane, Color.blue.darker().darker(),"keyword");
styleNumber = EditUtil.createStyle(textPane, Color.red,"number");
styleOperator = EditUtil.createStyle(textPane, Color.blue,"operator");
styleBracket = EditUtil.createStyle(textPane, Color.blue.darker(),"bracket");
styleString = EditUtil.createStyle(textPane, Color.gray,"string");
styleComment = EditUtil.createStyle(textPane, Color.cyan.darker(),"comment");
stylePrimitive = EditUtil.createStyle(textPane, Color.blue,"primitive");
styleLineComment = EditUtil.createStyle(textPane, Color.cyan.darker(),"lineComment");
StyleConstants.setBold(styleWord, false);
StyleConstants.setBold(styleNumber, true);
StyleConstants.setBold(styleOperator, true);
StyleConstants.setBold(styleString, false);
StyleConstants.setBold(styleComment, false);
StyleConstants.setBold(styleLineComment, false);
StyleConstants.setBold(styleKeyword, true);
StyleConstants.setBold(stylePrimitive, true);
}

public int scan(StyledDocument doc, char[] buffer, int start, int end){
EditUtil.setAttribute(doc,styleWord,start,end-start);
int i = start;
char c;
char tempC = 0;
lastSelectedAttribute = styleWord;
if(buffer.length == 0)
return 0;
try{
while(i1)tempC = buffer[i-2];
if(i>1 && ( tempC== ' ' || tempC == '\n' ||
tempC== '\t' || tempC == '(' ||
tempC == '{' || tempC == '[' ||
tempC=='\r' || tempC=='=')){
sb = new StringBuffer().append(c);
lastSelectedAttribute = styleWord;
for(;;){
c = buffer[i++];
if( c== ' ' || c=='\n'|| c =='\t'|| c=='}' ||
c==')' || c==']' || c=='\r' || c==';' ||
c=='(' || c=='[' || c=='{' || c == 0 || EditUtil.isOperator(c)){
i--;
break;
}
sb.append(c);
}
if(EditUtil.isKeyword(keywords,sb.toString()))
EditUtil.setAttribute(doc,styleKeyword,cur,sb.toString().length());
else if(sb.toString().startsWith("this."))
EditUtil.setAttribute(doc,styleKeyword,cur,4);
else if(EditUtil.isPrimitive(primitiveTypes,sb.toString()))
EditUtil.setAttribute(doc,stylePrimitive,cur,sb.toString().length());
}
break;
}
}
}catch(ArrayIndexOutOfBoundsException e){}
return i;
}

}

import java.awt.*;
import java.awt.event.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;

public class NewEditPane extends JTextPane implements DocumentListener, CaretListener, MouseListener{

protected StyledDocument doc = null;
protected Segment text = new Segment();
protected int caret = 0;
protected int inputLen = 0;
protected NewJavaUtil scanner = null;
protected boolean insertHappened = false;
protected boolean removeHappend = false;
protected boolean fileRead = true;
protected Element root=null, root1 = null;
protected int line = 0, start=0;
protected Element lineElement = null;
private Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.yellow);

public NewEditPane(){
super(new DefaultStyledDocument());
setSize(1600,400);
setPreferredSize(new Dimension(1600,400));
Insets insets = new Insets(2, 11, 2, 11);
setMargin(insets);
addCaretListener(this);
addMouseListener(this);
doc = (StyledDocument) getDocument();
doc.addDocumentListener(this);
setOpaque(true);
setDoubleBuffered(true);
setForeground(Color.black);
setBackground(Color.white);
}

public void setFile(String filename){
scanner = new NewJavaUtil(this);
try{
read(new FileReader(filename), null);
}catch(IOException e){ return;}
scanAll();
invalidate();
highlight(0);
}

public void read (Reader in, Object obj) throws IOException{
doc.removeDocumentListener(this);
super.read(in, obj);
doc = (StyledDocument) getDocument();
doc.addDocumentListener(this);
repaint();
}

public void caretUpdate(CaretEvent e){
painter(); // line highlight
}

public void insertUpdate(DocumentEvent e){
caret = e.getOffset();
inputLen = e.getLength();
insertHappened = true;
}

protected void handleStyleOnInsert(int index){
if(index <= 0)
return;
char[] chars = text.array;
AttributeSet currentStyle = getCharacterAttributes();
String str = (String)currentStyle.getAttribute(StyleConstants.NameAttribute);
int start = EditUtil.getStartOfLine(chars, index-1);
int end = EditUtil.getEndOfLine(chars,index+inputLen);
int i = scanner.scan(doc,chars,start,end+1);
end = EditUtil.getEndOfLine(chars,i);
scanner.scan(doc,chars,i+1,end+1);
}

public void removeUpdate(DocumentEvent e){
caret = e.getOffset();
inputLen = 0;
removeHappend = true;
}

public void changedUpdate(DocumentEvent e){}

public void repaint(){
Rectangle r = this.getVisibleRect();
repaint(1, r.x, r.y, r.width, r.height);
}

protected void paintComponent(Graphics g){
super.paintComponent(g);
try{
doc.getText(0, doc.getLength(), text);
}
catch(BadLocationException e1){
return;
}
if(insertHappened || removeHappend){
handleStyleOnInsert(caret);
insertHappened = false;
removeHappend = false;
}
}

/* scans the entire text and set the attributes. */
private void scanAll(){
try {
doc.getText(0, doc.getLength(), text);
}
catch(BadLocationException e) {
return;
}
char[] chars = text.array;
scanner.scan(doc,chars,0,chars.length);
}
// line highlight
public void painter(){
root = this.getDocument().getDefaultRootElement();
line = root.getElementIndex(getCaretPosition());
lineElement = root.getElement(line);
start = lineElement.getStartOffset();
highlight(start);
repaint();
}

public boolean getScrollableTracksViewportWidth(){
return false;
}

public void setSize(Dimension d){
if(d.width

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
spiderwick
Offline
Joined: 2007-08-12
Points: 0

oh. i forgot the Extension Filter code:

[code] import java.io.File; import javax.swing.filechooser.*;
public class ExtFilter extends FileFilter
{
String[] extensions; String description;
public ExtFilter(String ext) {this (new String[] {ext},null);}

public ExtFilter(String[] exts, String descr)
{
extensions = new String[exts.length];
for (int i=exts.length-1;i>=0;i--){extensions[i]=exts[i].toLowerCase();}
description=(descr==null?exts[0]+" files":descr);
}
public boolean accept(File f)
{
if (f.isDirectory()) {return true;}
String name=f.getName().toLowerCase();
for (int i=extensions.length-1;i>=0;i--)
{if (name.endsWith(extensions[i])) {return true;} }
return false;
}
public String getDescription() {return description;}
}
[/code]