Page 139 - DCAP408_WEB_PROGRAMMING
P. 139

Unit 8: File I/O




          The Basics                                                                            Notes

          Syntax Highlighting works like this: you give the text to the lexer, it goes through it and gives
          it back to you piece by piece and tells you what color to make each piece.

          Streams and Readers

          The syntax lexers accept your document through Streams and Readers. Fortunately it is very
          easy to turn just about anything into a Stream or a Reader.  Java comes with many prebuilt
          classes for this purpose. A FileReader or a StringReader could be used. The demo uses a custom
          DocumentReader.

          Tokens

          The lexer returns Tokens. Tokens don’t tell you the actual color that the text should be, but they
          do give you enough information to figure it out. The token contains such useful information as
          the type of text, a description of the text, and the position of the text in the file.


                 Example: Basic Example
          JavaLexer  syntaxLexer  =  new  JavaLexer(new  StringReader(myDocumentText));
          Token  t;
          while  ((t  =  syntaxLexer.getNextToken())  !=  null){
                  //  color  the  part  of  the  document
                  //  to  which  the  token  refers  here.
          }
          The Demo uses a look-up hashtable to get the color of the text based on the description from the
          token.
          SimpleAttributeSet  style;


          style  =  new  SimpleAttributeSet();
          StyleConstants.setFontFamily(style,  “Monospaced”);
          StyleConstants.setFontSize(style,  12);
          StyleConstants.setBackground(style,  Color.white);
          StyleConstants.setForeground(style,  Color.black);
          StyleConstants.setBold(style,  false);
          StyleConstants.setItalic(style,  false);
          styles.put(“body”,  style);


          style  =  new  SimpleAttributeSet();
          StyleConstants.setFontFamily(style,  “Monospaced”);
          StyleConstants.setFontSize(style,  12);
          StyleConstants.setBackground(style,  Color.white);
          StyleConstants.setForeground(style,  Color.blue);






                                           LOVELY PROFESSIONAL UNIVERSITY                                   133
   134   135   136   137   138   139   140   141   142   143   144