HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

When Java first came out, one of its acknowledged weaknesses was the lack of an advanced set of GUI components. This was especially evident in the text controls, which lacked many of the advanced features found in the native text controls of operating systems such as Windows. With the release of the Java Foundation Classes (also known as Swing), Java finally had a robust and sophisticated collection of controls, especially text controls.

With this in mind, this series of articles will show how to build a simple syntax, with emphasis on text control using Swing's Model View Controller (MVC) architecture and JTextPane. The control will handle keyword highlighting by changing the font style to a bold format. It will handle both single-line ("//Š") and multiline ("/*Š*/") comments by changing the style to an italic format and the font color to a user-defined one. Strings (any text between quotes) and numbers will also be formatted by having their respective font colors changed to user-defined ones. The control will support all of the Java language keywords as a default, but will allow the user to change or completely replace the keywords with their own.

Explanation of MVC in Swing Document Model
The Swing set of GUI components provides a complete package of components, classes and interfaces that rely heavily on the Model View Controller architecture. With this in mind, I've provided the following brief overview of what MVC means to Swing, especially the Swing text components.

Model View Controller in Simple Terms
The Model View Controller architecture is a commonly used OO technique to distinguish the data, the rendering of the data and user interaction with the rendering and the data. In MVC the Model holds all the data necessary for the View, the View is responsible for deciding how the data in the Model is presented and the Controller is used to handle events and processing between the View and Model (see Figure 1).

Figure 1
Figure 1:

How does the Model View Controller apply to Swing's text class, specifically the Document classes?

Swing uses a condensed version called UI delegate in which the Controller and View are combined into one, with the Model remaining separate, as shown in Figure 2. In this article we're concerned primarily with implementation of a Model, specifically the Document model used throughout the Swing text controls.

Figure 2
Figure 2:

Pros and Cons of Using Swing's Model View Controller Architecture
Using MVC throughout the Swing class hierarchy has allowed Sun Microsystems to create a very sophisticated architecture that allows all sorts of advanced customizations. The only downside is that the complexity of performing even simple tasks with the controls tends to intimidate newcomers to the Swing style of doing things. Hopefully, these articles will clear up at least part of the confusion in working with the text controls.

The Document
In Swing, as I mentioned before, the Document serves as the Model in the MVC architecture. So what is the Document? It's an interface describing the core functions of the Model and has several implementations already present in the Swing text package: the AbstractDocument class, the PlainDocument class and the DefaultStyledDocument class.

Every Document is composed of a series of elements arranged in hierarchical order. These elements, which are represented by the Element interface (part of the com.sun.java.swing.text package in JDK 1.1.x), serve many purposes. They break the Document into logical sections and can tell you where you are within the Document. In our case the primary use of the elements is to determine our place quickly so we only have to deal with the related text without having to sort through all of the text all of the time.

While the Element interface is great for navigation, it doesn't tell you much about how it looks. This is done by the AttributeSet interface. The AttributeSet also has a more complex descendant called the MutableAttributeSet interface, which allows us to modify the attribute rather than merely access information from it. The default implementation of these interfaces is provided in the SimpleAttributeSet class. Using this class you can modify font size and color, italic and bold styles and many other characteristics.

These two classes now enable us to determine our position, get a representative chunk of text and make modifications to the text attributes accordingly.

Let's take a look at how we could get our position using the Element interface. Assume that we've been provided with a variable (int offs) that represents the current offset in all the text, not just the chunk in the Element. The "this" variable points to a Document implementation.

Element element =
this.getParagraphElement(offs);
int elementStartOffs =
element.getStartOffset();
int elementTextLen =
element.getEndOffset() -
element.getStartOffset();
String elementText = this.getText
(elementStartOffs, elementTextLen);

The elementText variable now represents only the text within the bounds of our particular element. This eliminates the need to have to parse through all the text. To better explain this, let's say you're chugging along, typing merrily away. As long as your cursor is always at the last character of text, backing up and determining where the next space is (which would signify a word break) is pretty easy. But what happens if you suddenly decide to go back and place the cursor in the middle of all the text you just typed? How do you determine where you are without processing through all the text? This is where using the Elements, as we're doing above, saves us.

Modifying the attributes of a select portion of text is also easy, as in our next example:

Now let's say the elementText variable we mentioned above contains the text "import java.util.*;" (as in preceding code). The "this" variable references an instance of some DefaultStyledDocument object.

SimpleAttributeSet bold =
new SimpleAttributeSet();
StyleConstants.setBold(bold, true);
String word = elementText.subString(0,6);
this.remove(offs - word.length(),
word.length());
this.insertString(offs - word.length(),
word, bold);

First we create the attribute by using a new instance of the SimpleAttributeSet. Using the StyleConstants setBold method will modify our new attribute variable. Notice that we have to remove the text we're about to change with the Document's remove method. Then a call is sent to insertString, passing in the position, the string and the current attribute settings. By doing this we can change the formatting of the text "import" to a bold font:

Now that we know how to work with and modify the Document's text, let's look at how we're actually going to go about setting up our syntax highlighting. For simplicity's sake I chose to create a new class called CodeDocument that extends the DefaultStyledDocument.

As I mentioned earlier, three classes are already coded for us in Swing: the AbstractDocument, which is the base class for all the Swing Document implementations; the PlainDocument for straight text handling; and the DefaultStyledDocument, which handles all the fancy text formatting commonly found in RTF or HTML files. Since we'll need the text formatting attributes, it was a no-brainer to decide to extend DefaultStyledDocument (see code above).

Capturing text input turned out to be quite easy: we just override the insertString (int offs, String str, AttributeSet a) method and place our own functionality here. The insertString method is called whenever any kind of text is entered, either by keystroke (making the str value just one character) or by programmatically adding text to the Document. To support this added functionality we'll add some attributes to our CodeDocument class. We'll need to keep track of the current word that we're on, so we'll have an attribute called "word" of type String. We'll also keep track of the current position, modifying it each time we enter our overridden insertString() method. We'll call this attribute currentPos of type int. We could use an attribute to hold the bold settings so we don't have to keep creating one. We could also use an attribute of type Vector to hold all the keywords. We'll call this variable "keywords."

Now the class looks something like what is contained in Listing 1.

We have two functions in this new class: the overridden insertString and a new function called checkForKeyword. The former is called every keystroke, or any other time text is inserted. The first thing we do is call the superclass's insertString function to ensure that the string is properly put into the Document's text. We then see whether the string is one character (most likely from a keystroke) or multiple characters (which we won't handle at the moment). If it's one character, we get that character and compare it: any character that signifies a word break (defined as a space, "{", "}", "(", ")", carriage return or ";") will cause us to call the checkForKeyword function.

This function basically pulls off the current word from our current position (stored in the currentPos attribute) and compares it with the list of keywords that the class has. If a match is found, the word is removed and replaced with the same word, but with bold-style formatting. Walking through the function, the first thing it does is set a local variable called "offs" equal to the current position. From this position, as discussed above, we can get the current element text, based on the element's offsets (using the element.getStartOffset() and element.GetEndOffset() functions). If the text retrieved has a zero length, we can safely return from the function.

The next chunk of code handles the problem of typing some text for a while and then moves the cursor back to someplace in the middle of the newly entered text. If this is the case, the offs variable needs to be translated to match up properly with the array of characters in the element text. With this taken care of, we're ready to start walking backwards through the text. Backwards, you say? Yes, because the offs variable represents the last typed position, which would be at the end of a word. So we set up a loop and continue to move back from our position until we hit a delimiter (defined as "{", "}", "(", ")" or a space). Now we have a word, and we can compare it against our list of keywords using the Vector class's contains() function.

Well, we're nowhere near being done, but we have the main outline of a class ready, we know the methods we need to override, and we know the key concepts we need to get the job done. In the next article we'll see how this all comes together in a working Document class that we can then plug into a JTextPane.

References

  1. Topley, K. (1998). Core Java Foundation Classes. Prentice Hall PTR. Englewood Cliffs, NJ: Prentice-Hall.
  2. Eckstein, R., Loy, R., and Wood, D. (1998). Java Swing. O'Reilly and Associates.
About the Author Jim Crafton is a staff consultant with Computer Sciences Corporation, where he specializes in object-oriented development. He also develops advanced graphics software for Windows and the BeOS. He can be reached at [email protected] and has a Web site at http://w3.one.net/~ddiego/

	

Listing 1: 

import com.sun.java.swing.*; 
import com.sun.java.swing.text.*; 
import java.util.*; 
import java.awt.*; 

public class CodeDocument extends DefaultStyledDocument{ 
  private String word = ""; 
  private SimpleAttributeSet bold = new SimpleAttributeSet(); 
  private SimpleAttributeSet normal = new SimpleAttributeSet(); 
  private int currentPos = 0; 
  private Vector keywords = new Vector(); 

  public CodeDocument() { 
   //set the bold attribute 
   StyleConstants.setBold(bold, true); 
  } 

  private void checkForKeyword(){ 
    int offs = this.currentPos; 
    Element element = this.getParagraphElement(offs); 
    String elementText = ""; 
    try{ 
      //this gets our chuck of current text for the element we’re on 
      elementText = this.getText(element.getStartOffset(),
	  element.getEndOffset() - element.getStartOffset()); 
    } 
    catch(Exception ex){ 
      //whoops! 
      System.out.println("no text"); 
    } 
    int strLen = elementText.length(); 
    if (strLen == 0) {return;} 
    int i = 0; 

    if (element.getStartOffset() > 0){ 
      //translates backward if neccessary 
      offs = offs - element.getStartOffset(); 
    } 
    if ((offs >= 0) && (offs <= strLen-1)){ 
      i = offs; 
      while (i >0){ 
      //the while loop walks back until we hit a delimiter 
        i--; 
        char charAt = elementText.charAt(i); 
        if ((charAt == ' ') | (i == 0) | (charAt =='(') | (charAt ==')') | 
            (charAt == '{') | (charAt == '}')){ //if i == 0 then we're at the begininng 
          if(i != 0){ 
            i++; 
          } 
          word = elementText.substring(i, offs);//skip the period 

          String s = word.trim().toLowerCase(); 
          //this is what actually checks for a matching keyword 
          if (keywords.contains(s)){ 
            try{ 
              //remove the old word and formatting 
              this.remove(currentPos - word.length(), word.length()); 
              /*replace it with the same word, but new formatting 
              *we MUST call the super class insertString method here, otherwise we 
              *would end up in an infinite loop !!!!!*/ 
              super.insertString(currentPos - word.length(), word, bold); 
            } 
            catch (Exception ex){ 
              ex.printStackTrace(); 
            } 
          } 
          break; 
        } 
      } 
    } 
  } 

  public void insertString(int offs, 
                          String str, 
                          AttributeSet a) throws BadLocationException{ 
    if (offs < 0){ 
      return; 
    } 
    currentPos = offs; 
    char strChar; 
    super.insertString(offs, str, normal); 

    int strLen = str.length(); 
    if (strLen > 1){ 

    } 
    else{ 
      strChar = str.charAt(0); 

      switch (strChar){ 
        case ('{'):case ('}'):case (' '): case('\n'): 
        case ('('):case (')'):case (';'):case ('.'):{ 
          checkForKeyword(); 
          wordStart = offs; 
        } 
        break; 
      }//end switch 
    } 
  } 

  public Vector getKeywords(){ 
    return this.keywords; 
  } 

  public void setKeywords(Vector aKeywordList){ 
    if (aKeywordList != null){ 
      this.keywords = aKeywordList; 
    } 
  } 
} 

  

 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.