Java highlighted keywords

Source: Internet
Author: User

Write your own text editor (1): highlight keywords
I. Highlighted content:
The content to be highlighted includes:
1. keywords, such as public, Int, true, etc.
2. operators, such as +,-, *,/, etc.
3. Number
4. highlight a string, such as "example of string"
5. highlight a single line comment
6. Highlight multi-line comments

2. Core methods for implementing highlight:
Styleddocument. setcharacterattributes (INT offset, int length, attributeset S, Boolean replace)

3. Select the text editor.
The multiline text editors provided in Java include jtextcomponent, jtextarea, jtextpane, and jeditorpane. however, because the text in syntax coloring uses multiple styles, styleddocument is used for the document of these text editors.
Jtextarea uses plaindocument, which cannot be colored in multiple formats.
Jtextpane and jeditorpane use styleddocument, which can be used by default.
To implement syntax coloring, You can inherit from defaultstyleddocument and set it as the et of these text editors, or you can directly use jtextpane and jeditorpane. For convenience, you can directly use jtextpane here.

4. When to color.
When characters in the text editor are inserted or deleted, the text content changes. Check and color the text.
To monitor the changes in the text content, add a documentlistener listener to the document and perform coloring in its removeupdate and insertupdate.
The changedupdate method is called only when the text attributes such as foreground color, background color, and font style change.

@ Override <br/> Public void changedupdate (documentevent E) {</P> <p >}</P> <p> @ override <br/> Public void insertupdate (documentevent E) {<br/> try {<br/> coloring (styleddocument) E. getdocument (), E. getoffset (), E. getlength (); <br/>} catch (badlocationexception E1) {<br/> e1.printstacktrace (); <br/>}</P> <p> @ override <br/> Public void removeupdate (deleentevent E) {<br/> try {<br/> // because the cursor is immediately followed by the two sides of the word after deletion, the length is not required <br/> coloring (styleddocument) E. getdocument (), E. getoffset (), 0); <br/>} catch (badlocationexception E1) {<br/> e1.printstacktrace (); <br/>}< br/>

 

5. Coloring range:
POs: the position of the indicator before the change.
Len: the number of changed characters.
For example, public or int
In the word "publicint", insert a space in "public" and "int" and convert it to "Public int". A word is changed to two, in this case, "public" and "int" are colored.
The coloring range is the position of P in public and the position of T in int plus 1, that is, the subscript starting from the word before POs and the subscript ending from the Word POS + Len. in the preceding example, the color range is "Public int ".
The indexofwordstart method is provided to obtain the subscript of the word before pos. The indexofwordend method is used to obtain the subscript of the word after POS.

Public int indexofwordstart (document DOC, int POS) throws badlocationexception {<br/> // locate the first non-word character from the POS. <br/> for (; POS> 0 & iswordcharacter (Doc, pos-1); -- POS); <br/> return Pos; <br/>}</P> <p> Public int indexofwordend (document DOC, int POS) throws badlocationexception {<br/> // locate the first non-word character from the POS. <br/> for (; iswordcharacter (Doc, POS); ++ POS); <br/> return Pos; <br/>}</P> <p>

A character is a valid character of a word: letters, numbers, and underscores.

Public Boolean iswordcharacter (document DOC, int POS) throws badlocationexception {<br/> char CH = getcharat (Doc, POS ); // obtain the character at the position of the POs in the document <br/> If (character. isletter (CH) | character. isdigit (CH) | CH = '_') {return true ;}< br/> return false; <br/>}</P> <p>

Therefore, the color range is [start, end]:

Int start = indexofwordstart (Doc, POS); <br/> int end = indexofwordend (Doc, POS + Len); <br/>

6. Keyword coloring.
Start with the subscript of the coloring range. If it starts with a letter or an underscore, it indicates a word, then the word is obtained first. If the word is a keyword, the keyword is colored, if not, perform normal coloring. after the word is colored, continue the subsequent coloring process. the colored characters are no longer colored.

Public void coloring (styleddocument doc, int POs, int Len) throws badlocationexception {<br/> // gets the words affected after insertion or deletion. <br/> // For example, if "public" is inserted after B, a space is changed to "Pub LIC". Then there are two words to be processed: "pub" and "LIC" <br/> // The obtained range is the position before P in pub and the position behind C in Lic. <br/> int start = indexofwordstart (Doc, pos); <br/> int end = indexofwordend (Doc, POS + Len); </P> <p> char ch; <br/> while (start <End) {<br/> CH = getcharat (Doc, start); <br/> If (character. isletter (CH) | CH = '_') {<br/> // if it starts with a letter or underscore, the description is the word <br/> // POS is the last subscript after processing <br/> Start = colouringword (Doc, start ); <br/>} else {<br/> // swingutilities. invokelater (New colouringtask (Doc, POs, wordend-pos, normalstyle); <br/> ++ start; <br/>}</P> <p> Public int colouringword (styleddocument doc, int POS) throws badlocationexception {<br/> int wordend = indexofwordend (Doc, POS); <br/> string word = Doc. gettext (Pos, wordend-Pos); // the word to be colored </P> <p> If (keywords. contains (Word) {<br/> // if it is a keyword, the keywords are colored. Otherwise, the common coloring is used. <br/> // note that the doc attribute cannot be modified during insertupdate and removeupdate methods. <br/> // but we need to modify the doc attribute again. Therefore, we need to put this task out of this method for execution. <br/> // to achieve this goal, you can use a new thread, but put it in the swing event queue for easier processing. <br/> swingutilities. invokelater (New colouringtask (Doc, POs, wordend-pos, keywordstyle); <br/>} else {<br/> swingutilities. invokelater (New colouringtask (Doc, POs, wordend-pos, normalstyle); <br/>}</P> <p> return wordend; <br/>}</P> <p> because the document attributes cannot be modified in the insertupdate and removeupdate methods, the coloring task is placed out of these two methods, so swingutilities is used. invokelater. <br/> private class colouringtask implements runnable {<br/> private styleddocument Doc; <br/> private style; <br/> private int Pos; <br/> private int Len; </P> <p> Public colouringtask (styleddocument doc, int POs, int Len, Style) {<br/> this.doc = Doc; <br/> This. pos = Pos; <br/> This. len = Len; <br/> This. style = style; <br/>}</P> <p> Public void run () {<br/> try {<br/> // here, the characters are colored. <br/> Doc. setcharacterattributes (Pos, Len, style, true); <br/>}catch (exception e) {}< br/>}</P> <p> 

7. Source Code
The code for completing keyword coloring is as follows. You can compile and run the Code directly. The coloring processing of numbers, operators, strings, and so on will be further explained in future tutorials.

Import Java. AWT. color; <br/> Import Java. util. hashset; <br/> Import Java. util. set; </P> <p> Import javax. swing. jframe; <br/> Import javax. swing. jtextpane; <br/> Import javax. swing. swingutilities; <br/> Import javax. swing. event. documentevent; <br/> Import javax. swing. event. documentlistener; <br/> Import javax. swing. text. badlocationexception; <br/> Import javax. swing. text. document; <br/> Import javax. swing. text. style; <br/> Import javax. swing. text. styleconstants; <br/> Import javax. swing. text. styleddocument; </P> <p> public class highlightkeywordsdemo {<br/> Public static void main (string [] ARGs) {<br/> jframe frame = new jframe (); </P> <p> jtextpane editor = new jtextpane (); <br/> editor. getdocument (). adddocumentlistener (New syntaxhighlighter (editor); <br/> frame. getcontentpane (). add (editor); </P> <p> frame. setdefaclocloseoperation (jframe. exit_on_close); <br/> frame. setsize (500,500); <br/> frame. setvisible (true ); <br/>}</P> <p>/** <br/> * highlight a text field when it contains characters inserted or deleted. <br/> * syntax highlighting is required. The document of the text input component must be styled document. therefore, do not use jtextarea. you can use jtextpane. <br/> * @ author Biao <br/> */<br/> class syntaxhighlighter implements documentlistener {<br/> private set <string> keywords; <br/> private style keywordstyle; <br/> private style normalstyle; </P> <p> Public syntaxhighlighter (jtextpane editor) {<br/> // style used for coloring <br/> keywordstyle = (styleddocument) Editor. getdocument ()). addstyle ("keyword_style", null); <br/> normalstyle = (styleddocument) Editor. getdocument ()). addstyle ("keyword_style", null); <br/> styleconstants. setforeground (keywordstyle, color. red); <br/> styleconstants. setforeground (normalstyle, color. black); </P> <p> // prepare keywords <br/> KEYWORDS = new hashset <string> (); <br/> keywords. add ("public"); <br/> keywords. add ("protected"); <br/> keywords. add ("private"); <br/> keywords. add ("_ int9"); <br/> keywords. add ("float"); <br/> keywords. add ("double"); <br/>}</P> <p> Public void coloring (styleddocument doc, int POs, int Len) throws badlocationexception {<br/> // gets the words affected by insertion or deletion. <br/> // For example, if "public" is inserted after B, a space is changed to "Pub LIC". Then there are two words to be processed: "pub" and "LIC" <br/> // The obtained range is the position before P in pub and the position behind C in Lic. <br/> int start = indexofwordstart (Doc, pos); <br/> int end = indexofwordend (Doc, POS + Len); </P> <p> char ch; <br/> while (start <End) {<br/> CH = getcharat (Doc, start); <br/> If (character. isletter (CH) | CH = '_') {<br/> // if it starts with a letter or underscore, the description is the word <br/> // POS is the last subscript after processing <br/> Start = colouringword (Doc, start ); <br/>} else {<br/> swingutilities. invokelater (New colouringtask (Doc, start, 1, normalstyle); <br/> + + start; <br/>}</P> <p>/** <br/> * Color Words, returns the subscript of the end of the word. <br/> * @ Param doc <br/> * @ Param POS <br/> * @ return <br/> * @ throws badlocationexception <br/> */<br/> Public int colouringword (styleddocument Doc, int POS) throws badlocationexception {<br/> int wordend = indexofwordend (Doc, POS); <br/> string word = Doc. gettext (Pos, wordend-Pos); </P> <p> If (keywords. contains (Word) {<br/> // if it is a keyword, the keywords are colored. Otherwise, the common coloring is used. <br/> // note that the doc attribute cannot be modified during insertupdate and removeupdate methods. <br/> // but we need to modify the doc attribute again. Therefore, we need to put this task out of this method for execution. <br/> // to achieve this goal, you can use a new thread, but put it in the swing event queue for easier processing. <br/> swingutilities. invokelater (New colouringtask (Doc, POs, wordend-pos, keywordstyle); <br/>} else {<br/> swingutilities. invokelater (New colouringtask (Doc, POs, wordend-pos, normalstyle); <br/>}</P> <p> return wordend; <br/>}</P> <p>/** <br/> * obtain the character whose subscript is at the POs position in the document. <br/> * If the POS is Doc. getlength () returns the end of a document and does not throw an exception. if the POS is <0, an exception is thrown. <br/> * The valid POS value is [0, Doc. getlength ()] <br/> * @ Param doc <br/> * @ Param POS <br/> * @ return <br/> * @ throws badlocationexception <br/> */<br/> Public char getcharat (document DOC, int POS) throws badlocationexception {<br/> return Doc. gettext (Pos, 1 ). charat (0); <br/>}</P> <p>/** <br/> * returns the subscript of the word starting with the subscript POS. â ± wor ^ d â ± (^ indicates POs, â ± indicates the subscript of start or end) <br/> * @ Param doc <br/> * @ Param POS <br/> * @ return <br/> * @ throws badlocationexception <br/> */<br/> Public int indexofwordstart (document DOC, int POS) throws badlocationexception {<br/> // locate the first non-word character from the POS. <br/> for (; POS> 0 & iswordcharacter (Doc, pos-1); -- POS); </P> <p> return Pos; <br/>}</P> <p>/** <br/> * returns the subscript of the word ending when the subscript is POS. â ± wor ^ d â ± (^ indicates POs, â ± indicates the subscript of start or end) <br/> * @ Param doc <br/> * @ Param POS <br/> * @ return <br/> * @ throws badlocationexception <br/> */<br/> Public int indexofwordend (document DOC, int POS) throws badlocationexception {<br/> // locate the first non-word character from the POS. <br/> for (; iswordcharacter (Doc, POS); ++ POS); </P> <p> return Pos; <br/>}</P> <p>/** <br/> * true is returned if one character is a letter, number, or underscore. <br/> * @ Param doc <br/> * @ Param POS <br/> * @ return <br/> * @ throws badlocationexception <br/> */<br/> Public Boolean iswordcharacter (document DOC, int POS) throws badlocationexception {<br/> char CH = getcharat (Doc, POS); <br/> If (character. isletter (CH) | character. isdigit (CH) | CH = '_') {return true ;}< br/> return false; <br/>}</P> <p> @ override <br/> Public void changedupdate (documentevent E) {</P> <p >}</P> <p> @ override <br/> Public void insertupdate (documentevent E) {<br/> try {<br/> coloring (styleddocument) E. getdocument (), E. getoffset (), E. getlength (); <br/>} catch (badlocationexception E1) {<br/> e1.printstacktrace (); <br/>}</P> <p> @ override <br/> Public void removeupdate (deleentevent E) {<br/> try {<br/> // because the cursor is immediately followed by the two sides of the word after deletion, the length is not required <br/> coloring (styleddocument) E. getdocument (), E. getoffset (), 0); <br/>} catch (badlocationexception E1) {<br/> e1.printstacktrace (); <br/>}</P> <p>/** <br/> * Complete the coloring task <br/> * @ author biao <br/> */<br/> private class colouringtask implements runnable {<br/> private styleddocument Doc; <br/> private style; <br/> private int Pos; <br/> private int Len; </P> <p> Public colouringtask (styleddocument doc, int POs, int Len, Style) {<br/> this.doc = Doc; <br/> This. pos = Pos; <br/> This. len = Len; <br/> This. style = style; <br/>}</P> <p> Public void run () {<br/> try {<br/> // here, the characters are colored. <br/> Doc. setcharacterattributes (Pos, Len, style, true); <br/>} catch (exception E) {}< br/>}< br/>

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.