Hello All,
I'm trying to write a simple html editor that will highlight tags, and it does, but if the user types the caret jumps to the very end of the document, how can I stop this from happening?
here's my code:
import javax.swing.*;
/**
* Main frame for the program.
* @author Bill
*
*/
public class MainFrame extends JFrame {
private static final long serialVersionUID = -7853618434340029314L;
JTextPane editor = new JTextPane();
SyntaxDocument2 sd = new SyntaxDocument2();
/**
* Make a main frame.
*/
public MainFrame() {
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize( 500, 500 );
editor.setDocument( sd );
this.add( editor );
this.setVisible( true );
}
/**
* entry point of the program
* @param args command line arguments
*/
public static void main(String[] args) {
new MainFrame();
}
}
/**
*
*/
import java.awt.Color;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
/**
* @author Bill
*
*/
public class SyntaxDocument2 extends DefaultStyledDocument {
private static final long serialVersionUID = 8802669064394912853L;
SimpleAttributeSet norm = new SimpleAttributeSet();
SimpleAttributeSet tag = new SimpleAttributeSet();
SimpleAttributeSet string = new SimpleAttributeSet();
/**
* Sets some stuff up.
*/
public SyntaxDocument2() {
StyleConstants.setForeground( tag, Color.green );
StyleConstants.setForeground( string, Color.red );
}
/**
* @see javax.swing.text.AbstractDocument#insertString(int, java.lang.String, javax.swing.text.AttributeSet)
*/
@Override
public void insertString( int offs, String str, AttributeSet a )
throws BadLocationException {
super.insertString( offs, str, a );
String str2 = super.getText( 0, super.getLength() );
super.remove( 0, super.getLength() );
int off = 0;
char c;
boolean inTag=false;
boolean inString=false;
for(int i = 0;i<str2.length();i++,off++) {
c=str2.charAt( i );
switch( c ) {
case '<':
inTag=true;
super.insertString( off, ""+c, tag );
break;
case '>':
inTag=false;
super.insertString( off, ""+c, tag );
break;
case '"':
if(inTag) {
inString=!inString;
super.insertString( off, ""+c, string );
} else {
super.insertString( off, ""+c, norm );
}
break;
default:
if(inTag) {
if(inString) {
super.insertString( off, ""+c, string );
} else {
super.insertString( off, ""+c, tag );
}
} else {
super.insertString( off, ""+c, norm );
}
break;
}
}
}
}