Welcome!

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

Related Topics: Java IoT

Java IoT: Article

Reflecting a Bean onto a Table

Reflecting a Bean onto a Table

Originally I planned to continue with the syntax-highlighting CodeDocument component, but I decided to switch gears and discuss some neat uses for the JTable component that comes with Swing (my apologies go out to all those weeping in the aisles, anxiously awaiting more syntax-highlighting code...oh, just a second, let's dab the tears away before continuing).

One of the cool features of the JTable component is its ability to be customized, right down to the individual table cell. This feature, plus another unspeakably cool feature of Java itself (called reflection, but more on that later), will allow us to build a simple Component Inspector similar to what you'd find in IDEs like Borland's JBuilder or Symantec's VisualCafé.

What Is a Component Inspector?
A Component Inspector is used to look at (and edit) the various properties that make a GUI control, like a text box or a progress bar. The Inspector is activated by selecting a control, then editing the properties through the Inspector. This idea is used not only in Java IDEs, but also in programming tools like Visual Basic and Borland's Delphi (see Figures 1 and 2.).

Our Component Inspector will consist of a JFrame, which will house a table with two columns, and a couple of labels above the table, to tell us general information about the component we're looking at. What we should end up with can be seen in Figure 3.

Now, making a super-sophisticated Component Inspector would be really cool, but the whole point of this article is to learn more about JTables and reflection, so to test this out we'll just have another window that contains a variety of controls, and each time we click on one of them the Component Inspector will be updated. Take a look at Figure 4 to see what this window looks like.

Tables, Tables...and More Tables
Like the rest of Swing, JTable uses the Model View Controller architecture to allow all sorts of complex customization. One type allows the programmer to specify exactly how each table cell is rendered by the table. A table cell - the individual element at the intersection of a given row and column - can be customized as to how it looks (how it renders itself for the user) and how it's edited. Not only can a JTable be customized at the cell level, but you can also write a simple table model class that can prevent columns from being edited. This is what we want to do since the left-hand column will only need to display values, not edit them. So let's just jump in.

The first thing we're going to look at is the DefaultTableModel class, which inherits from the AbstractTableModel. We could have chosen to subclass the AbstractTableModel, but we would have had to implement everything ourselves. Since the only piece of functionality we want to add at this point is to lock the leftmost column against being edited, it's much simpler to extend an already functional class - namely, DefaultTableModel. To prevent column 0 from being edited, we override the functionality of the method isCellEditable(), which is called whenever the Table Model receives notification that a cell needs to edited. If the function returns true, editing is allowed; if false, then editing is prevented. By returning false at the appropriate times, we can easily prevent column 0 from being edited. Take a look at the code in Listing 1.

The first thing we do is to add all the constructors of the DefaultTableModel so they can be called from our class. Next, we override the isCellEditable() method. In this method we check for what column is being requested. If it's 0, we automatically return false; otherwise we call the super class's isCellEditable method to handle any remaining cases.

Now let's play around a bit and learn how to customize the Table rendering. As I mentioned before, each cell that gets rendered can be customized with its own renderer, which is associated with the class type of the value in the cell. Let's say you had a cell at column 0 and row 0 that was a String object. You could associate a custom cell renderer with any String object, and the table would automatically use your renderer to paint the cell instead of its own. Not only would it paint the cell at column 0, row 0, using your renderer, but any other values in the table that were String objects would also get painted using the same renderer. Any object can be a renderer so long as it implements the TableCellRenderer interface (in the com.sun.java.swing.table package). The TableCellRenderer interface has only one method, getTableCellRendererComponent(), which needs to return a Component object. The arguments of the method can tell you whether the cell is selected or not, whether it has focus, what the value of the cell is, the column and row of the cell, and the actual table component the cell belongs to. A very simple implementation could be the one in Listing 2.

To use this, look at Listing 3.

A cell renderer can also be a component itself. For example, let's say that for boolean objects we want a checkbox to appear (there already is a cell renderer available for boolean values built into the JTable implementation, courtesy of the nice folks at Sun). We could just create a new sub class of JCheckBox and implement the TableCellRenderer interface and we'd be all set to go. Let's look at the example in Listing 4.

One thing to remember is that the value argument of getTableCellRendererComponent() can be null, but you still have to return a component of some sort or the table will throw a sea of exceptions when it tries to draw itself, especially if you scroll down through a number of rows.

Now that we can customize our display of call data, if we were going to allow editing, we'd want to create a cell editor now as well. In this example, however, we're just going to try and display information only.

Mirror, Mirror on the Wall...
Okay, so we know how to display our data, but where do we get it from and how do we get at it? This is accomplished using a very cool - and very powerful - feature of Java called reflection (also sometimes referred to as class or JavaBean introspection). What you read here will be used not only in this article, but again when we come back to our CodeDocument class and start adding features like dropping down a listbox full of the variable's methods and attributes just typed in.

Reflection allows the programmer to ask an object to describe itself by listing all of its methods, fields and method signatures. It is literally like walking up to a person and asking them to describe themselves for you, tell you their family history (who their parents were, where they were born, etc.), list all the things they can do and so on. Like reflection, JavaBeans introspection allows you to ask for all sorts of detailed information pertaining to the specific instance of a bean at runtime, which is what allows tools like JBuilder and VisualCafé to list all the properties of a particular bean.

Reflection starts by obtaining a reference to the object's Class attribute. This is accomplished by the getClass() method in the Object base class. Once you have a Class object, you can get the rest of the information you need - and can even call the methods you retrieve! Let's look at Listing 5 for an example.

The first thing we do in the code is to get the Class object from the argument aValue. Now remember, because we've defined the aValue argument as an object, it could represent anything at runtime - a JFrame, a Hashtable or anything else. Once we have a reference to the class object, we can get the class name through the getName() method, which returns a fully qualified name (i.e., instead of "String", it returns "java.lang.String"). Any of the constructors, methods or fields of the class can be retrieved through calls like getDeclaredMethod() (for a single method) or getDeclaredMethods() (for all of the methods) (for constructors, you would use getDeclaredConstructors(), and so on). Using the getDeclaredMethods() method, we can loop through all the methods and print out their names using the Method class's getName() function. When retrieving a single method, you have to pass in the method name as well as an array of class objects that represent the arguments of the method. So let's say we were going to try and find out if the object had a setElementAt() method. We could do this as shown in Listing 6.

The array of class objects tells Java what types are in the argument list. If there are no arguments, you can just pass in null. Invoking the method is similar to retrieving it. You pass in an array of objects that are the actual values you want passed as arguments to the method. That would be as in Listing 7.

Presto! You have magically invoked a method, determining everything at runtime!

Getting BeanInfo
As I mentioned earlier, if the object you're dealing with is a JavaBean, you can get even more information - things like what kind of property editors it uses, what the display name is, whether a particular property of the JavaBean knows how to paint itself, and many others.

To start, you use the Introspector static class method getBeanInfo(), passing in the Class object of the bean or component you're interested in. The Introspector is nice enough to package everything in a neat interface called BeanInfo that has a number of methods to retrieve things like the icon associated with the bean, as well as all the properties, events and methods for that bean. The item we're really interested in is the list of properties, retrieved through a call to the getPropertyDescriptors() method of the BeanInfo class. This method gives us an array of PropertyDescriptors from which we can get information like the "read" and the "write" methods of the property, the property editor class (if one exists) and other information as well. Another short example of using this is the code in Listing 8.

All this code does is output the available properties with their names, and read and write method names to the command line. If you were interested in finding out what was in any of the properties, you could use the getReadMethod() function and invoke the read method as described earlier.

Tune in next time...
That's it for this month. We'll wrap it up in the next article by combining the two features we discussed: the customization of tables with reflection and JavaBean introspection, and we'll have ourselves a bona fide Component Inspector. In doing this, we'll delve further into the PropertyInspector class, learning how to paint the property and how to display any custom editors that exist for the property. Hope you found this as fascinating as I did writing it! See you next time....

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 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...
"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.
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...
"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.
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.
"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.
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.
"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.
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...
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...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, 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. 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 ...
SYS-CON Events announced today that CHEETAH Training & Innovation 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. CHEETAH Training & Innovation is a cloud consulting and IT training firm specializing in improving clients cloud strategies and infrastructures for medium to large companies.
SYS-CON Events announced today that Datanami 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. Datanami is a communication channel dedicated to providing insight, analysis and up-to-the-minute information about emerging trends and solutions in Big Data. The publication sheds light on all cutting-edge technologies including networking, storage and applications, and thei...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...