Java IoT Authors: Elizabeth White, Yeshim Deniz, Liz McMillan, Pat Romanski, Paul Simmons

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
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
"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.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
The Founder of NostaLab and a member of the Google Health Advisory Board, John is a unique combination of strategic thinker, marketer and entrepreneur. His career was built on the "science of advertising" combining strategy, creativity and marketing for industry-leading results. Combined with his ability to communicate complicated scientific concepts in a way that consumers and scientists alike can appreciate, John is a sought-after speaker for conferences on the forefront of healthcare science,...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at @ThingsExpo, James Kirkland, Red Hat's Chief Archi...
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...
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...