Java IoT Authors: Yeshim Deniz, Liz McMillan, Mano Marks, Elizabeth White, Pat Romanski

Related Topics: Java IoT

Java IoT: Article

More on Syntax Highlighting

More on Syntax Highlighting

Last month we discussed the use of Swing's Document model to create a syntax-highlighting Document model that we could just plug into JTextPane and use. This month we'll continue with that and add complete support for comments, strings and numbers. We'll also cover how easy it is to actually use the model we've developed, and test things out as we go along.

To start things out let's try and use what we have so far. If we look at the code below we can see that plugging the Document we've created into a JTextPane component is quite easy. Defining the keywords is also very easy.

JTextPane editor = new JTextPane();
CodeDocument doc = new CodeDocument();
Vector keywords = new Vector();

We could have just created the CodeDocument on the fly and passed it in as an argument to the constructor of the JTextPane class, but then the keywords for the Document wouldn't have been set and we'd have had to retrieve the Document and then add them.

By running the code above and typing in some text, we get the window in Figure 1 to come up.

A word of caution: If you use this and the first word you type in is in your keywords list, you¹ll get an exception. This is a known bug on the Swing Web site (for more information look at                           .http://developer.java.sun.com/developer/bugParade/bugs/4128967.html) with no known workaround. You may also notice that when you type for a while and then move the cursor back to a previous position and start typing again, the JTextPane doesn't quite repaint itself correctly. This is also a known bug of the JTextPane (for more information see http://developer.java.sun.com/developer/ bugParade/bugs/4127974.html). This has been fixed in Swing version 1.1.

Now you can test the modifications we'll be making to the CodeDocument class.

Changing the insertString Method
Some of you may have noticed that the Document Model code we developed in the previous article worked only if you actually typed in the text manually. If we had called the insertString method and passed in a string with a length longer than one character, the syntax highlighting wouldn't have worked. To fix that we'll make a simple change, moving the code that actually did the comparing to another method, and changing the insertString method to support any size string. We'll create a method called processChar that will actually do the work of checking the kind of character we're dealing with and, in turn, call the correct method to handle that character. To make the whole thing work, we can then just loop through each of the characters in the string that's passed into the insertString method, starting at the offset position (the offs variable passed into the insertString method) and ending at the offset plus the length of the string passed in. For each character we find we can call the processChar method, and voila! We can now handle any size string. To get an idea of the code, take a look below.

public void insertString(int offs,
String str,
AttributeSet a) throws BadLocationException{
super.insertString(offs, str, normal);

int strLen = str.length();
int endpos = offs + strLen;
int strpos;
for (int i=offs;i<endpos;i++){
currentPos = i;
strpos = i - offs;
currentPos = offs;

The only problem with the solution above is that when reading large chunks of text you may notice a slowdown in JTextPane's performance while it loads and parses all the text. A possible solution would be to use a thread to handle any text not immediately visible to the user, parse it in the background and then...well, that'll be the subject of a future article!

Adding String Support
Now that we can support entered text of any size, let's add highlighting support for strings. Adding string support isn't too hard now that we have the basic pieces in place. We'll add a variable that we'll use to keep track of whether we're entering a string. If this flag is turned on, any text we enter following the double quote ("") will be colored in a different foreground color. Also, if this flag is turned on, no keyword processing will occur. A carriage return will automatically shut the flag off. We'll need to keep track of the start position where the flag was first turned on. This will allow us to type in some text representing a string, hit the carriage return and type other stuff, and then put the caret back on the line where the string was and resume entering the string text ­ all the while keeping the formats correct. We'll also need a variable that represents the style attribute we want for strings.

In addition to variables we'll need some new methods. For strings we'll create a checkForString() method that will determine whether we're inside a string. If it finds that we are, the mode variable will be set appropriately (this will be explained in more detail a few paragraphs down). We'll also need a method called insertTextString() that will actually reinsert the properly formatted string.

Adding Number Support
Adding support for numbers is similar to adding support for strings. We'll add a variable to hold the style attribute for numbers, and also add two more methods: checkForNumber() and insertNumberString().

Like strings, the checkForNumber() method determines whether we're actually entering valid digits. If we are, it sets the CodeDocument's mode accordingly. Like insertTextString, insertNumberString inserts the properly formatted text as a number.

Adding Comment Support
Comments are handled in a similar manner. Two new methods are needed, checkForComment() and insertCommentString(). Like numbers and text, the checkForComments method determines if a comment block has been started (it checks for the "/*" combination to start a comment and the "*/" to end a comment block). If it has, it changes the attributes of the entered text by calling the insertCommentString() method. Again, like numbers and strings, the insertCommentString() changes the formatting attri-butes of the string accordingly, and then inserts into the document. Another private variable is needed to hold the formatting attributes for comments.

Putting It All Together
Now it's time to get down and dirty. We're finally going to look at the whole process, first in general terms and then in more detail using code examples. As we mentioned earlier, the original insertString method of the CodeDocument class was changed, and much of the logic was moved to a new method called processChar(), thus allowing us to handle not only single keystrokes, but also to programmatically insert multiple character strings. ProcessChar() works by making certain assumptions about what characters will follow other characters. Based on this, it sets the insert mode for the current position of incoming text. Based on this mode (which is simply a private integer variable), it can then determine which insertXXXString() method to call.

For example, when it encounters the character '9', it figures there's a very good chance that this is the start of a number or that a number is currently in the process of being entered. To verify this it calls the checkForNumber() method. If checkForNumber() determines that we're still entering a number, it sets the mode to the number entry mode. If it discovers any other character present, however, such as a space, a parenthesis or a letter, it sets the mode to the default text entry mode (the number entry mode is represented by the static constant NUMBER_MODE, while the text entry mode is represented by the static constant TEXT_MODE). The other checkForXXX() methods work in a similar fashion. After the checkForXXX() method has returned, the mode will have been set correctly and, based on this, the proper insertXXXString() method can be called. If the mode is in TEXT_MODE, the formatting is left alone.

Now look at the code in Listing 1 for method processChar. The first thing the method does is to check if we're in COMMENT_MODE. Because comments can include anything (aside from the comment-terminating characters), we'll let the mode default to COMMENT_MODE; otherwise we'll change it to default to TEXT_MODE, which is the standard text entry mode (no formatting). Next, a switch statement is created based on the character passed to the processChar method. As mentioned before, the method works on the assumption that the character being entered belongs to one of five groups (generic text, keywords, strings, numbers or comments), and that the case statements are grouped accordingly. Characters equaling the numbers '1' through '9' cause a check for numbers; characters equaling '*' or '/' suggest the possible start or end of a comment block, and a check is made; and so on. Once the switch statement is finished executing, a final check is made for quoted strings if we're still in TEXT_MODE. Finally, depending on which mode we're in, a call is made to the appropriate insertXXXString method.

There are four check methods: checkForComment(), checkForKeyword(), checkForNumber() and checkForString(). While there are some differences from the original checkForKeywords() method, the basic idea, as discussed last month, is the same. We retrieve the current element, get the text from it, find our position in the element and then, starting at the end, we walk backward until a delimiter of some sort is found and then set the mode accordingly. Let's look at some of the checkForString() method's code to examine this more closely. We'll assume we already have the correct offset from the Document's element.

int quoteCount = 0;
if ((offs >= 0) && (offs <= strLen-1)){
i = offs;
while (i >0){
//the while loop walks back until we hit a delimiter

char charAt = elementText.charAt(i);
if ((charAt == '"')){
quoteCount ++;
int rem = quoteCount % 2;
mode = (rem == 0) ? TEXT_MODE: STRING_MODE;

The code is fairly simple: we loop backward until we run out of characters to process, each time comparing a character from the element text. If the character is a double quote (" "), we add one to the local variable called quoteCount. Once we're done with the loop, we check the remainder of the quoteCount divided by two and assign the results to another local variable called rem. Why do this? Again, this is another assumption about the way words are put together. Since quotes always come in pairs, if our remainder isn't equal to zero, we know we're "inside" a string quotation. Otherwise we can safely assume that we're "outside" and are just entering normal text.

And Finally...
I think at this point I've probably run out of column space. We now have a syntax-highlighting Document class that supports any user-defined set keywords, plus string, number and comment highlighting (see Listings 2 and 3). We've also seen how easy it is to incorporate our Document class into the JTextPane control to test our results as we go along. In the next article we'll add some more user-definable properties so you can change the color of highlighted string, comments, keywords and so on. We'll also look at adding support for a kind of "smart editor" à la Borland's Code Insight features in their IDE editors.


  1. Topley, K. (1998). Core Java Foundation Classes. Prentice Hall PTR. Prentice-Hall Inc.
  2. Eckstein, R., Loy, R, and Wood, D. (1998) Java Swing. O'Reilly and Associates Inc.

More Stories By Jim Crafton

Jim Crafton is software developer currently doing a variety of work in C++, C#, and Java. He is the author of the Visual Component Framework (more at http://vcf-online.org/), an advanced C++ application framework. He's also interested in graphics, particularly 3D graphics using tools like Houdini and ZBrush.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@ThingsExpo Stories
Bert Loomis was a visionary. This general session will highlight how Bert Loomis and people like him inspire us to build great things with small inventions. In their general session at 19th Cloud Expo, Harold Hannon, Architect at IBM Bluemix, and Michael O'Neill, Strategic Business Development at Nvidia, discussed the accelerating pace of AI development and how IBM Cloud and NVIDIA are partnering to bring AI capabilities to "every day," on-demand. They also reviewed two "free infrastructure" pr...
In his keynote at @ThingsExpo, Chris Matthieu, Director of IoT Engineering at Citrix and co-founder and CTO of Octoblu, focused on building an IoT platform and company. He provided a behind-the-scenes look at Octoblu’s platform, business, and pivots along the way (including the Citrix acquisition of Octoblu).
Data is an unusual currency; it is not restricted by the same transactional limitations as money or people. In fact, the more that you leverage your data across multiple business use cases, the more valuable it becomes to the organization. And the same can be said about the organization’s analytics. In his session at 19th Cloud Expo, Bill Schmarzo, CTO for the Big Data Practice at Dell EMC, introduced a methodology for capturing, enriching and sharing data (and analytics) across the organization...
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the USA and Europe, we work with a variety of customers from emerging startups to Fortune 1000 companies.
Financial Technology has become a topic of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 20th Cloud Expo at the Javits Center in New York, June 6-8, 2017, will find fresh new content in a new track called FinTech.
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists will look at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deli...
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
@ThingsExpo has been named the Most Influential ‘Smart Cities - IIoT' Account and @BigDataExpo has been named fourteenth by Right Relevance (RR), which provides curated information and intelligence on approximately 50,000 topics. In addition, Right Relevance provides an Insights offering that combines the above Topics and Influencers information with real time conversations to provide actionable intelligence with visualizations to enable decision making. The Insights service is applicable to eve...
SYS-CON Events announced today that Grape Up will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy.
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in compute, storage and networking technologies, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology, is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/...
Amazon has gradually rolled out parts of its IoT offerings in the last year, but these are just the tip of the iceberg. In addition to optimizing their back-end AWS offerings, Amazon is laying the ground work to be a major force in IoT – especially in the connected home and office. Amazon is extending its reach by building on its dominant Cloud IoT platform, its Dash Button strategy, recently announced Replenishment Services, the Echo/Alexa voice recognition control platform, the 6-7 strategic...
Judith Hurwitz is president and CEO of Hurwitz & Associates, a Needham, Mass., research and consulting firm focused on emerging technology, including big data, cognitive computing and governance. She is co-author of the book Cognitive Computing and Big Data Analytics, published in 2015. Her Cloud Expo session, "What Is the Business Imperative for Cognitive Computing?" is scheduled for Wednesday, June 8, at 8:40 a.m. In it, she puts cognitive computing into perspective with its value to the busin...
Cognitive Computing is becoming the foundation for a new generation of solutions that have the potential to transform business. Unlike traditional approaches to building solutions, a cognitive computing approach allows the data to help determine the way applications are designed. This contrasts with conventional software development that begins with defining logic based on the current way a business operates. In her session at 18th Cloud Expo, Judith S. Hurwitz, President and CEO of Hurwitz & ...
Cybersecurity is a critical component of software development in many industries including medical devices. However, code is not always written to be robust or secure from the unknown or the unexpected. This gap can make medical devices susceptible to cybersecurity attacks ranging from compromised personal health information to life-sustaining treatment. In his session at @ThingsExpo, Clark Fortney, Software Engineer at Battelle, will discuss how programming oversight using key methods can incre...