Welcome!

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

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