Enable keyword highlighting by writing the jtextpane component

Source: Internet
Author: User

Package my2;

Import java. util. stringtokenizer;
Import java. AWT .*;
Import java. AWT. event .*;
Import javax. Swing .*;
Import javax. Swing. Text .*;
Import javax. Swing. Text. rtf. rtfeditorkit;
/**
* Special keyword processing panel
* @ Author Administrator
*
*/
Public class mytextpane extends jtextpane {
/**
*
*/
Private Static final long serialversionuid =-66377652770879651l;
Protected stylecontext m_context;
Protected defaultstyleddocument m_doc;
Private mutableattributeset keyattr, normalattr;
Private mutableattributeset bracketattr;
Private mutableattributeset inputattributes = new rtfeditorkit ()
. Getinputattributes ();
/**
* All keywords
*/
Private Final Static string [] _ keys = new string [] {"select", "from ",
"Where", "like", "and", "or", "order", "group", "sum", "AVG ",
"Not", "in", "CREATE", "Grand", "null", "Count", "Max", "min ",
"Start", "with", "Connect", "Update", "delete", "set", "values ",
"View", "table", "as", "distinct", "into", "Drop", "is", "on ",
"Exists", "by", "Tree", "table", "Cust", "Union", "dual ",
"Trigger", "function", "procedure", "begin", "end", "for", "loop ",
"While", "insert", "Count", "if", "else", "then", "commit ",
"Rollback", "Return", "declare", "when", "elsif", "open", "Fetch ",
"Close", "exit", "exception", "execute "};
/**
* Excluded character sets
*/
Private Final Static char [] _ character = new char [] {'(', ')', ';',
':', '\ T',' \ n', '+ ','-','*','/'};
/**
* Initialization, including the keyword color and non-Keyword color
*/
Public mytextpane (){
Super ();
M_context = new stylecontext ();
M_doc = new defastystyleddocument (m_context );
This. setdocument (m_doc );
This. addkeylistener (New keyadapter (){
Public void keyreleased (keyevent ke ){
Dealsinglerow ();
}
});
// Display attributes with the predefined keywords
Keyattr = new simpleattributeset ();
Styleconstants. setforeground (keyattr, color. Red );
// Display attributes of plain text
Normalattr = new simpleattributeset ();
// Styleconstants. setfontfamily (normalattr, "serif ");
Styleconstants. setbold (normalattr, false );
Styleconstants. setforeground (normalattr, color. Black );
Bracketattr = new simpleattributeset ();
Styleconstants. setforeground (bracketattr, color. Red );
// Styleconstants. setfontfamily (bracketattr, "serif ");
Styleconstants. setbold (bracketattr, true );
}
/**
* Set the color of braces.
* @ Param _ text
*/
Private void setbracketcolor (string _ text ){
Int Len = _ text. Length ();
For (INT I = 0; I <Len; I ++ ){
Char CH = _ text. charat (I );
If (CH = '{' | CH = '}'){
M_doc.setcharacterattributes (I, 1, bracketattr, false );
}
}
}
/**
* Determines whether a character is in the excluded character column.
* @ Param _ CH
* @ Return
*/
Private Boolean ischaracter (char _ CH ){
For (INT I = 0; I <_ character. length; I ++ ){
If (_ CH = _ character [I]) {
Return true;
}
}
Return false;
}
/**
* Set the keyword color.
* @ Param _ key
* @ Param _ start
* @ Param _ Length
* @ Return
*/
Private int setkeycolor (string _ key, int _ start, int _ length ){
For (INT I = 0; I <_ keys. length; I ++ ){
Int li_index = _ key. indexof (_ keys [I]);
If (li_index <0 ){
Continue;
}
Int li_legnth = li_index + _ keys [I]. Length ();
If (li_legnth = _ key. Length ()){
If (li_index = 0) {// process a single keyword, for example, if Else.
M_doc.setcharacterattributes (_ start, _ keys [I]. Length (),
Keyattr, false );
} Else {// case where there are characters before the keyword to be processed, such as :) If; else
Char ch_temp = _ key. charat (li_index-1 );
If (ischaracter (ch_temp )){
M_doc.setcharacterattributes (_ start + li_index,
_ Keys [I]. Length (), keyattr, false );
}
}
} Else {
If (li_index = 0) {// If the keyword to be processed is followed by a character, for example, if (end ;)
Char ch_temp = _ key. charat (_ keys [I]. Length ());
If (ischaracter (ch_temp )){
M_doc.setcharacterattributes (_ start, _ keys [I]. Length (),
Keyattr, false );
}
} Else {// handling case where both the front and back of a keyword have characters, for example, if ()
Char ch_temp = _ key. charat (li_index-1 );
Char ch_temp_2 = _ key. charat (li_legnth );
If (ischaracter (ch_temp) & ischaracter (ch_temp_2 )){
M_doc.setcharacterattributes (_ start + li_index,
_ Keys [I]. Length (), keyattr, false );
}
}
}
}
Return _ Length + 1;
}
/**
* Processing data in one row
* @ Param _ start
* @ Param _ end
*/
Private void dealtext (INT _ start, int _ end ){
String text = "";
Try {
TEXT = m_doc.gettext (_ start, _ end-_ start). touppercase ();
} Catch (badlocationexception e ){
E. printstacktrace ();
}
If (text = NULL | text. Equals ("")){
Return;
}
Int xstart = 0;
// Analyze keywords ---
M_doc.setcharacterattributes (_ start, text. Length (), normalattr, false );
Mystringtokenizer ST = new mystringtokenizer (text );
While (St. hasmoretokens ()){
String S = ST. nexttoken ();
If (S = NULL)
Return;
Xstart = ST. getcurrposition ();
Setkeycolor (S. tolowercase (), _ start + xstart, S. Length ());
}
Setbracketcolor (text );
Inputattributes. addattributes (normalattr );
}
/**
* When modifying text
* Obtain the row where the cursor is located and only process the row.
*/
Private void dealsinglerow (){
Element root = m_doc.getdefaultrootelement ();
// The current row of the cursor
Int cursorpos = This. getcaretposition (); // The Position of the cursor
Int line = root. getelementindex (cursorpos); // The current row
Element para = root. getelement (line );
Int start = para. getstartoffset ();
Int end = para. getendoffset ()-1; // remove the \ r character
Dealtext (START, end );
}
/**
* Call this method when initializing the panel,
* Search for keywords of the entire length
*/
Public void syntaxparse (){
Element root = m_doc.getdefaultrootelement ();
Int li_count = root. getelementcount ();
For (INT I = 0; I <li_count; I ++ ){
Element para = root. getelement (I );
Int start = para. getstartoffset ();
Int end = para. getendoffset ()-1; // remove the \ r character
Dealtext (START, end );
}
}
}
/**
* While analyzing strings, record the location of each token
*
*/
Class mystringtokenizer extends stringtokenizer {
String sval = "";
String oldstr, STR;
Int m_currposition = 0, m_beginposition = 0;
Mystringtokenizer (string Str ){
Super (STR ,"");
This. oldstr = STR;
This. Str = STR;
}
Public String nexttoken (){
Try {
String S = super. nexttoken ();
Int Pos =-1;
If (oldstr. Equals (s )){
Return S;
}
Pos = Str. indexof (S + sval );
If (Pos =-1 ){
Pos = Str. indexof (sval + S );
If (Pos =-1)
Return NULL;
Else
Pos + = 1;
}
Int xbegin = POS + S. Length ();
STR = Str. substring (xbegin );
M_currposition = m_beginposition + Pos;
M_beginposition = m_beginposition + xbegin;
Return S;
} Catch (Java. util. nosuchelementexception ex ){
Ex. printstacktrace ();
Return NULL;
}
}
// Returns the position of the token in the string.
Public int getcurrposition (){
Return m_currposition;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.