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

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