Welcome!

Java IoT Authors: Elizabeth White, Yeshim Deniz, Pat Romanski, Liz McMillan, Chris Schwarz

Related Topics: Java IoT

Java IoT: Article

Text Controls by Swing

Text Controls by Swing

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).

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.

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.

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.

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
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"DX encompasses the continuing technology revolution, and is addressing society's most important issues throughout the entire $78 trillion 21st-century global economy," said Roger Strukhoff, Conference Chair. "DX World Expo has organized these issues along 10 tracks with more than 150 of the world's top speakers coming to Istanbul to help change the world."
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
The financial services market is one of the most data-driven industries in the world, yet it’s bogged down by legacy CPU technologies that simply can’t keep up with the task of querying and visualizing billions of records. In his session at 20th Cloud Expo, Karthik Lalithraj, a Principal Solutions Architect at Kinetica, discussed how the advent of advanced in-database analytics on the GPU makes it possible to run sophisticated data science workloads on the same database that is housing the rich...
SYS-CON Events announced today that Massive Networks 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. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, has been named "Bronze Sponsor" of 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. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech has been named “Media Sponsor” of 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. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of 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. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...