Welcome!

Java IoT Authors: Liz McMillan, Elizabeth White, Pat Romanski, Yeshim Deniz, Carmen Gonzalez

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
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, June 6-8, 2017, at the Javits Center in New York City, NY and October 31 - November 2, 2017, Santa Clara Convention Center, CA. 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 EARP Integration 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. EARP Integration is a passionate software house. Since its inception in 2009 the company successfully delivers smart solutions for cities and factories that start their digital transformation. EARP provides bespoke solutions like, for example, advanced enterprise portals, business intelligence systems an...
Existing Big Data solutions are mainly focused on the discovery and analysis of data. The solutions are scalable and highly available but tedious when swapping in and swapping out occurs in disarray and thrashing takes place. The resolution for thrashing through machine learning algorithms and support nomenclature is through simple techniques. Organizations that have been collecting large customer data are increasingly seeing the need to use the data for swapping in and out and thrashing occurs ...
Amazon started as an online bookseller 20 years ago. Since then, it has evolved into a technology juggernaut that has disrupted multiple markets and industries and touches many aspects of our lives. It is a relentless technology and business model innovator driving disruption throughout numerous ecosystems. Amazon’s AWS revenues alone are approaching $16B a year making it one of the largest IT companies in the world. With dominant offerings in Cloud, IoT, eCommerce, Big Data, AI, Digital Assis...
SYS-CON Events announced today that Progress, a global leader in application development, has been named “Bronze Sponsor” of 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. Enterprises today are rapidly adopting the cloud, while continuing to retain business-critical/sensitive data inside the firewall. This is creating two separate data silos – one inside the firewall and the other outside the firewall. Cloud ISVs oft...
The 21st International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Digital Transformation, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 21st International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. @ThingsExpo Silicon Valley Call for Papers is now open.
As cloud adoption continues to transform business, today's global enterprises are challenged with managing a growing amount of information living outside of the data center. The rapid adoption of IoT and increasingly mobile workforce are exacerbating the problem. Ensuring secure data sharing and efficient backup poses capacity and bandwidth considerations as well as policy and regulatory compliance issues.
SYS-CON Events announced today that Interoute has been named “Bronze Sponsor” of 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. Interoute is the owner operator of Europe's largest network and a global cloud services platform, which encompasses over 70,000 km of lit fiber, 15 data centers, 17 virtual data centers and 33 colocation centers, with connections to 195 additional partner data centers. Our full-service Unifie...
In order to meet the rapidly changing demands of today’s customers, companies are continually forced to redefine their business strategies in order to meet these needs, stay relevant and continue to see profitable growth. IoT deployment and development is integral in this transformation, and today businesses are increasingly seeing the value of investing their resources into IoT deployments. These technologies are able increase ROI through projects such as connecting supply chains or enabling sm...
SYS-CON Events announced today that Progress, a global leader in application development, has been named “Bronze Sponsor” of 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. Enterprises today are rapidly adopting the cloud, while continuing to retain business-critical/sensitive data inside the firewall. This is creating two separate data silos – one inside the firewall and the other outside the firewall. Cloud ISVs ofte...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
SYS-CON Events announced today that DivvyCloud 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. DivvyCloud software enables organizations to achieve their cloud computing goals by simplifying and automating security, compliance and cost optimization of public and private cloud infrastructure. Using DivvyCloud, customers can leverage programmatic Bots to identify and remediate common cloud problems in rea...
SYS-CON Events announced today that Outscale, a global pure play Infrastructure as a Service provider and strategic partner of Dassault Systèmes, 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. Founded in 2010, Outscale simplifies infrastructure complexities and boosts the business agility of its customers. Outscale delivers a secure, reliable and industrial strength solution for its customers, which in...
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists will examine how DevOps helps to meet th...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of 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. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and management into a ...
SYS-CON Events announced today that A&I Solutions has been named “Bronze Sponsor” of 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. Founded in 1999, A&I Solutions is a leading information technology (IT) software and services provider focusing on best-in-class enterprise solutions. By partnering with industry leaders in technology, A&I assures customers high performance levels across all IT environments including: mai...
Every successful software product evolves from an idea to an enterprise system. Notably, the same way is passed by the product owner's company. In his session at 20th Cloud Expo, Oleg Lola, CEO of MobiDev, will provide a generalized overview of the evolution of a software product, the product owner, the needs that arise at various stages of this process, and the value brought by a software development partner to the product owner as a response to these needs.
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software in the hope of capturing value in IoT. Although IoT is relatively new in the market, it has already gone through many promotional terms such as IoE, IoX, SDX, Edge/Fog, Mist Compute, etc. Ultimately, irrespective of the name, it is about deriving value from independent software assets participating in an ecosystem as one comprehensive solution.
SYS-CON Events announced today that EARP 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. "We are a software house, so we perfectly understand challenges that other software houses face in their projects. We can augment a team, that will work with the same standards and processes as our partners' internal teams. Our teams will deliver the same quality within the required time and budget just as our partn...