import java.awt.Color;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class KeyWordCheck extends JFrame {
List section;
JTextPane textArea;
String red = "section";
String blue = ".bss|.data|.text";
String mainString = "section|.bss|.data|.text";
private int findLastNonWordChar(String text, int index) {
while (--index >= 0) {
if (String.valueOf(text.charAt(index)).matches(mainString)) {
break;
}
}
return index;
}
private int findFirstNonWordChar(String text, int index) {
while (index < text.length()) {
if (String.valueOf(text.charAt(index)).matches(mainString)) {
break;
}
index++;
}
return index;
}
JTextPane KeyWorPane;
public KeyWordCheck() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 400);
setLocationRelativeTo(null);
final StyleContext cont = StyleContext.getDefaultStyleContext();
final AttributeSet attrRed = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.RED);
final AttributeSet attrBlack = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.BLACK);
final AttributeSet attrBlue = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.BLUE);
DefaultStyledDocument doc = new DefaultStyledDocument() {
public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
super.insertString(offset, str, a);
String text = getText(0, getLength());
int before = findLastNonWordChar(text, offset);
if (before < 0) {
before = 0;
}
int after = findFirstNonWordChar(text, offset + str.length());
int wordL = before;
int wordR = before;
while (wordR <= after) {
if (wordR == after || String.valueOf(text.charAt(wordR)).matches(mainString)) {
if (text.substring(wordL, wordR).matches(red)) {
setCharacterAttributes(wordL, wordR - wordL, attrRed, false);
}
else if (text.substring(wordL, wordR).matches(blue)) {
setCharacterAttributes(wordL, wordR - wordL, attrBlue, false);
}
else {
setCharacterAttributes(wordL, wordR - wordL, attrBlack, false);
}
wordL = wordR;
}
wordR++;
}
}
public void remove(int offs, int len) throws BadLocationException {
super.remove(offs, len);
String text = getText(0, getLength());
int before = findLastNonWordChar(text, offs);
if (before < 0) {
before = 0;
}
int after = findFirstNonWordChar(text, offs);
if (text.substring(before, after).matches(red)) {
setCharacterAttributes(before, after - before, attrRed, false);
}
else if (text.substring(before, after).matches(blue)) {
setCharacterAttributes(before, after - before, attrBlue, false);
} else {
setCharacterAttributes(before, after - before, attrBlack, false);
}
}
};
textArea = new JTextPane(doc);
add(new JScrollPane(textArea));
setVisible(true);
}
public static void main(String args[])
{
new KeyWordCheck();
}
}