Welcome!

Java IoT Authors: Pat Romanski, Roger Strukhoff, Mehdi Daoudi, Liz McMillan, Elizabeth White

Related Topics: Java IoT

Java IoT: Article

Components, and Creating a Custom Property Editor

Components, and Creating a Custom Property Editor

This column discusses property editors and how to implement one for Java -specifically, how to make one work for our CodeDocument class. When last we talked, we saw how to build a CodeDocument class, but it wasn't something we could work with in a visual designer like JBuilder, say, or Visual Cafe. In this column we'll build a special case of the JTextArea component and add some specialty properties and property editors to support the CodeDocument class we worked on before. The code listings at the end of the article are excerpted from the complete code, which you can download from www.JavaDevelopersJournal.com.

Property Editors and How They Work
Basically, property editors allow you to edit a property. Wow! What a concept! Except that to make this work the IDE has to know what the property is. Luckily, since we're talking about Java, we have a neat little tool called Reflection that we can use to ask any given object, "What are you?" and get back a response like, "I'm a java.lang.String class object." Great, now we know what we're dealing with...but wait a minute...hold the bus. How do we know how to edit the object? "It's a string. How hard can it be?" you say. Well, if everything were a string, we'd have no problems, but things are a little more complicated than that. Granted, a string is easy to edit, but what about a color object, or a collection of items (like a vector)? Since a property can be any kind of object, we need to have a uniform way of explaining to the IDE how to edit that object, and, if necessary, supply a custom UI with which to edit the property. So the property editor interface provides just the thing we need, with methods to get and set the object in question, as well as methods for telling whether the property editor supports a custom UI editor.

Property editors by themselves don't do much good. For the IDE to "know" about them, the component whose properties we're interested in must publish BeanInfo.

The BeanInfo interface describes the component to the IDE with information such as the icon to display as a visual representation of the component and - you guessed it -a list of property descriptors. What do the property descriptors do? They describe properties! Each property descriptor contains information such as the name of the get and set methods, the name of the property, the class the property belongs to and, finally (and this is optional), the PropertyEditor class itself. Thus, when the user asks to edit a property, the IDE first retrieves the component's BeanInfo class and then the property descriptor for the desired property. If the property descriptor supports a custom editor, the custom editor is then loaded and the custom editor component is loaded and displayed for the user to work with (this usually takes place in a dialog of some sort -at least this is how JBuilder handles things).

Adding Our Own Property Editor for the CodeDocument
Let's take this knowledge and do something practical with it. Let's add a new component based on JTextPane, which automatically uses a Document model based on our CodeDocument class. We'll start with the code shown in Listing 1.

All right, that was pretty painless. What we're doing is calling the super class in the constructor and setting the document to a new instance of the CodeDocument class we developed previously. We're going to add a single property -call keywords -that will allow the developer to modify the CodeDocument keywords attribute. Doing this changes the set of keywords the CodeDocument looks for in its syntax highlighting process. Let's look at another example demonstrating this, in Listing 2.

So now we've added two methods that allow us to get and set keywords. We overloaded the setKeywords method to allow for either a vector of keywords or an array of strings (the array of string method simply converts the array to a vector and calls the vector version of the method).

This will become more important when we add our property editor later on. Notice that we didn't add an attribute of type Vector to the code -we're simply mapping any calls to get or set keywords directly back to the CodeDocument class. Now we have our component, and if we wanted to we could leave it at that. However, we wouldn't have a property editor working yet, thus defeating the point of this article!

The next thing we need to add is the BeanInfo class. BeanInfo is actually an interface that you need to implement in some other class to make things work. So let's create our BeanInfo implementation class, as seen in Listing 3.

So far this is pretty basic. As mentioned before, the BeanInfo methods allow an IDE to determine all sorts of information about the component and the properties it supports. In our implementation you'll notice we extend SimpleBeanInfo, a class that has all the methods of the BeanInfo stubbed out. Since there are a few other methods that aren't neccessary for us at this point, extending SimpleBeanInfo makes our life a little easier, allowing us to focus on just the parts we need. As mentioned earlier, getPropertyDescriptors() is the method called by the IDE to get all the property info. We'll return an array of property descriptors only for the properties we're interested in exposing to the IDE for user manipulation. In our case there will be only one element, for the keywords property. The getIcon() method will return either null or an image containing a 16x16 icon (black and white or color) that represents the component or a 32x32 icon (also black and white or color). The kind of icon is determined by the iconKind parameter passed into the method (the choices are ICON_COLOR_16x16, ICON_COLOR_32x32, ICON_MONO_16x16, and ICON_MONO_32x32). The getAdditionalBeanInfo() is supposed to call the super class and request more bean info from that class.

For now, let's look at the getPropertyDescriptors() method. In our implementation we need to supply only one element in the array. We don't need to worry about any of the super class properties. If we had another property that was a string -say, DocumentName -we wouldn't have to worry about it either. Why? Because objects like string and integer almost always have default property editors registered in the IDE and there's usually no need to register something else. But let's say that, instead of DocumentName, our property was called FileName, and we wanted to bring up some kind of file open dialog when the user tried to edit it. Now we'd want to supply a custom property editor for the string, causing a file open dialog to pop up when the property is edited. Back to our implementation. To set up the element properly, let's look at Listing 4.

The first thing we do is create a new instance of a PropertyDescriptor class by passing in the name of the property, the class it belongs to (in our case CodeTextPane) and the names of the get and set methods. The setDisplayName() method is used to define the text that will be displayed for your property, and the setShortDescription is used to populate tool tips with a short description of your property. The setPropertyEditorClass() method is used to set the class type for your property editor. It's important to set this up correctly; otherwise the property editor won't be picked up by the IDE. The class KeywordsEditor is the one we're going to create next, in case you're wondering where it came from. After this is done we'll create a new array of PropertyDescriptor objects (the propertyDescriptors variable) and put the new instance we created previously into the array. Then we just return the array.

The only other method we'll bother implementing in our implementation of BeanInfo is the getAdditionalBeanInfo() method. This is given in Listing 5.

By providing additional BeanInfo, we're giving the IDE more information about our object -specifically, about the object's super class. Similar to the PropertyDescriptor, we're returning an array of objects, each a reference to BeanInfo. In our implementation we call the Introspector's getBeanInfo() method to get the super class's bean info.

So far we've gone through all the steps neccessary to create a simple component (CodeTextPane) and supply an implementation of BeanInfo that properly exposes our property (keywords) and its custom editor class (KeywordsEditor). Now it's time to look at the property editor class directly. The class will actually have two parts: the first is the property editor class itself, KeywordsEditor (Listing 6a); the second is the custom editor component, KeywordsEditorComponent (Listing 6b).

The property editor interface is fairly easy to implement, especially when we extend from the PropertyEditorSupport class. Like the SimpleBeanInfo, it provides either stubs or simple implementations of the methods so we can concentrate on the few that are important to us. Since we want to support a custom editor component, we return true from the supportsCustomEditor() method that's called by the IDE. We also return an instance of our editor component in the getCustomEditor() method. Since getCustomEditor() returns a component, we can base our editor component on practically anything. Usually the component gets nested into some other container, like a dialog (this is the case with JBuilder), so basing it on JPanel is usually a good idea. The getJavaInitializationString() method returns a string that represents the Java code required to set the given property from the code editor. Whenever you change the property via your custom editor, this string will need to change as well. An example would be a property that is a font object. In your IDE's code editor, you might see something like this:

public void myInitMethod(){
//more code
this.setFont(new Font("SansSerif", 1, 12));
//more code...
}

The line "new Font("SansSerif", 1, 12)" would be provided to the IDE by whatever property editor is registered for the font property of the object. This string would be the return of the property editor's getJavaInitializationString() method. In our case the string might look like the following:

public void myInitMethod(){
//more code
codeTextPaneObj.setKeywords(new String[]{"foo","bar","blah",});
//more code...
}

Since there's no convenient way to represent a vector like this, we can use our second version of the setKeywords() method to pass in the new set of keywords. The implementation code for the getJavaInitializationString() method would look like Listing 7.

The getValue() method returns the current value of the property represented by the property editor (it's already implemented for us by the PropertyEditorSupport class). We then go through all the elements in the vector and assemble them into a string, returning this string when we're finished.

With this done we have our PropertyEditor class ready to go. Now we can take a look at designing the custom editor component. For starters let's take a look again at Listing 6b. The class is simple. It extends Panel (or JPanel if you want to have a Swing look) and has a constructor that takes one argument -a property editor object that's set to a private variable.

As it stands, the component will do absolutely nothing, so let's add a listbox to view all our keywords, an edit box to type in new keywords, two labels -one for the list and one for the edit box -and, finally, two buttons -one to add the information in the edit box and one to delete selected items from the keywords list. Take a look at Listing 8.

The keywords variable is a DefaultListModel, Swing's default implementation of a suitable list model for use in JList controls. So when we add items to the list, we don't bother calling the control methods; instead, we actually manipulate the keywords object. The JList is constructed by passing in the keywords object as its model, so everything is hooked up for us. The next thing we need to add is a private initialization method to set all the widget properties and hook up event listeners, as well as to configure a GridBagLayout to position all the controls properly. We'll call this method initEditor(), and instead of showing all the code here (you can see it on the JDJ Web site), I'm just going to present the sections relevant to the article. The main thing we need to catch are changes to the keywords list. Each time it changes, we need to call the property editor's setValue() method to inform it of a change, which in turn notifies any registered listeners that the property has changed. That way, when our editor component is dismissed, the property is in a valid state and the getJavaInitializationString() will return correct data. To accomplish this we register a listener with the keywords object as seen in Listing 9 (this takes place in the initEditor() method).

This ensures that any change to the keywords object will call the keywords_changed() method (a private method of the editor component), which properly updates the property editor. According to the Java documentation, you shouldn't actually modify the property editor value directly; instead, you should just send a new instance. To do that we end up with the code in Listing 10.

The method simply makes a copy of the elements in the keywords list and places them in a new instance of a vector that can then be sent to the property editor via the setValue() method.

One other thing of interest in the initEditor() method is the setting of the listbox to the current value of the property editor. This is accomplished in Listing 11.

The keywords object is cleared using the removeAll() method, and the property editor's value is retrieved through the getValue() method and then enumerated; the new elements are then added to the keywords list.

That's It, Folks!
We're done!

  • We've covered creating a new text component with support for our previously created CodeDocument class.
  • We've created a BeanInfo class to ensure that IDEs such as JBuilder are aware of the properties we're exposing and any custom features, like editors, we support.
  • We've created a property editor class to support our new property.
  • We've created a custom editor component that will allow us to edit that property in a visual way.
Whew! I hope this was helpful -let me know how it works for you by e-mailing me at [email protected].

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
SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
"Digital transformation - what we knew about it in the past has been redefined. Automation is going to play such a huge role in that because the culture, the technology, and the business operations are being shifted now," stated Brian Boeggeman, VP of Alliances & Partnerships at Ayehu, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, 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...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
SYS-CON Events announced today that Evatronix 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. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo 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 ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – 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 results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
SYS-CON Events announced today that T-Mobile exhibited 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. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...