JTable and bean binding

Hello everyone! After a long pause, here I am again :) Thought to power the blog again with the experience which I have gained past couple of years and hope to keep this as a future reference to me as well to remember what I have learned/gained during my work/study.

Okay! Let me begin the post. I have come across this scenario while I was working on a Java Swing application project at my office.

The problem: How to populate JTable with list of objects.

Typical and painful solution: Loop through the list and populate data column by column.
But it's a real pain when it comes to retrieve data as objects again from the table. We have to extract each property from each column in the table and create a new object with that data.

An easy and less complex/code solution: Bind beans to the table as rows.
If we can bind objects as it is to the table then its really easy to retrieve them as well. No need to iterate through columns anymore. I found this solution from this blog and total credit goes to the author.

This is how it works. There are two ways to bind beans to JTable.
  • Bean Table Model
  • Row Table Model
I have included both ways in the sample project please find the url for git repo at the end of this post. But here I only explain first method. Its really easy to understand second method once you learn the first. In the sample project, its just a matter of changing table model implementation in the source file to switch between those two methods.I have included all the source files in one package.

Following steps explain how to do it.

Step 1: Create a bean class
Step 2: Create the bean table model
Step 3: Bind the table model with JTable
Step 4: Retrieve data from the table
Screenshot of the demo application:
Yep. That's all. Its simple as that. Okay, time to go to bed :) I'll see you in another post. Triple gem bless you!

Git repository URL: JTableBeanDemo

P.S: You can also get the original source files from the blog link i have mentioned in the post.

No comments:

Post a Comment