Welcome!

Java IoT Authors: Liz McMillan, Elizabeth White, Pat Romanski, Stackify Blog, Progress Blog

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
DevOps at Cloud Expo – being held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real r...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
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 Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
SYS-CON Events announced today that TMC has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo and Big Data at Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Global buyers rely on TMC’s content-driven marketplaces to make purchase decisions and navigate markets. Learn how we can help you reach your marketing goals.
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that App2Cloud 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. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a mu...
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...
Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...