Home > Articles > Programming > Java

Creating a Custom Java Swing Tablemodel

  • Print
  • + Share This
If all you need a JavaSwing JTable for is to display data in a tabular fashion, this article is not for you. But if you have ever used the DefaultTableModel and found it wanting, or found yourself writing horribly unmaintainable code to manipulate the data or retrieve the data, read on. The solution is simple, says Marcus Zarra.
Like this article? We recommend

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.

The Data

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.

public class Widget { private String name; private double value; private String location; private int quantity; public String getName() { return name; } public void setName(String s) { name = s; } public double getValue() { return value; } public void setValue(double d) { value = value; } public String getLocation() { return location; } public void setLocation(String d) { location = d; } public int getQuantity() { return quantity; } public void setQuantity(int i) { quantity = i; } }

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.

  • + Share This
  • 🔖 Save To Your Account