Java Swing's JTable is easily one of the most powerful, customizable, and difficult pieces of the entire API. With the exception of JTree, no other object within the API can be used in so many ways.
There is a problem with this versatility, however. The JTable design is fairly complex, and (in an effort to make using it easier) Sun added several defaults to add users new to the API. Unfortunately, these defaults are commonly overused and incorrectly implemented. In this article, I will outline the creation of a custom table model and how it can help avoid duplication of data and creation of unmaintainable workarounds.
If all you ever need a JTable for is to display data in a tabular fashion, this article is not for you. However, if you have ever used the DefaultTableModel and either found it wanting or found yourself writing horribly unmaintainable code to manipulate the data or retrieve the data, read on-the answer is fairly simple.
In this article, you will implement a custom table model that stores data and gives an easy way to access and modify that data. First, let's define the data we want to display. This example has a large number of widgets, and each widget is its own object.
The class Widget is a very simple data object that adheres to the JavaBean standard. The next trick is to be able to view these widgets inside a JTable and to easily access and manipulate the widgets that are displayed in that table without a large amount of casting or complexity.