Understanding JTables

JTables… the Java swing component version of a datagrid used in .NET. It is often a misunderstood component by newbie Java programmers. In reality it is very easy to use once you understand the model behind it. Through the model you can manipulate the content of the JTable and make it bend to your will! Add that row! Delete that Row! Feel like a dictator after reading this entry…. on the Programming Underground!

Behind every good man is a good woman so they say. But in the world of Java every good JTable has an equally good model! While the JTable doesn’t actually need a model defined (a defaultmodel is created automatically) I strongly recommend that every developer explicitly define one. Once you have one defined and powering a JTable, you can use that model’s many methods for manipulating the data in a JTable. I will cover a few of these below and show you how you can use a few of them.

1. Defining the DefaultTableModel object – In your program make sure you have imported the swing package. Once you have that, defining a DefaultTableModel object is rather easy. The code looks something like this…

DefaultTableModel model = new DefaultTableModel();

Here we create a new instance of the DefaultTableModel() object and assign it to the variable “model”. Easy enough huh? Our variable model is going to serve as our reference to the object and it is the variable we will manipulate any time we want to manipulate the JTable’s data. Now I want to mention that there are several types of models out there and, like mentioned earlier, the DefaultTableModel is created automatically, but by defining it explicitly like this we can make it easy to manipulate the JTable through the its connected model. Think of the JTable as a window into the data the model is storing.

2. Adding columns to our JTable – Before we go and attach this model to a JTable, lets go ahead and create some columns. What is a JTable without columns right? Be it one or many columns, it is easy to add as many as you like to the model. You could even use a loop to create the columns dynamically if you wish. Giving you some flexibility as to how many columns can be shown at once. This makes it a great control for showing database tables and recordsets where you may not know how many columns there are.

You add columns through the use of the addColumn(“columntext”) method of the model object we just defined. Here I will define three columns… firstname, lastname, age.

// Using our model variable we call addColumn() and supply the text

model.addColumn("First Name");
model.addColumn("Last Name");
model.addColumn("Age");

Now how simple was that? Our model now contains three columns. Notice how we used the method of the model, not the JTable. Once we feed this model to the JTable we could still use this variable to manipulate the contents of the JTable (seen later).

3. Build the JTable using our model – Once we have some columns up and running in our model and such, we can go ahead and attach it to our “window” the JTable. This is really easy since one of the JTable’s constructors can take a Model object. So lets do that now and while we are at it, we can set its preferred size…

JTable mytable = new JTable(model);
mytable.setPreferredScrollableViewportSize(new Dimension(400, 300));

Now that we have the table model attached and we setup the size of the control, we can manipulate and retrieve data about the JTable from the underlying model. Some of the information we can get is…

a. getColumnCount() – Retrieve the number of columns in the model
b. getRowcount() – Retrieve the number of rows in the model
c. getColumns() – To return an enumeration of TableColumns in the model (to then loop through)

… and some of its more popular methods for manipulating the data….

d. insertRow() – To insert a new row
e. removeRow() – To kick a row out of the model
f. move Row() – Move a row up or down in the order
g. removeColumn() – To obliterate a column from the model
h. moveColumn() – To reorder the columns

plus many many more!

When you make changes to the underlying model you can see the changes in the JTable itself. Quite a few methods belong to the JTable but most of these are either to get access to the model, set the model, or make “visual” changes to the table such as color and general appearance.

The model handles the data, the JTable methods handle the view attributes including column width, row height etc. It does contain a few methods that can be used to manipulate the underlying model as well for those people who didn’t create their own default model. So I don’t want to hear “But martyr, these model methods are also available on the table!” Not all the JTable methods are equal to the model’s methods of the same name (like getValueAt() seen below)

There is another reason to my madness. By creating your own separate model object, you could (if you wanted to) attach the model to more than one JTable and manipulate all at once! Remember that JTable’s are just windows into the model, so each window could have their own look and style and size into the same data. Isn’t Java great that way?

4. Pulling out data from our new JTable using the model – One of the most common questions I see with regard to the JTable is the question “How do I get the info in cell at (row,column)?” well glad you asked because this is where the model comes in handy yet again using the getValueAt() method. Want to get the third column (age) from our second row? All you need is…

System.out.println((string) model.getValueAt(1,2));

Now this gets the cell object at that cell position. So we must make sure to cast it to string so that it will print. Another distinction I want to make is that since we are using this method of the model, we are getting the position in the model, not the display in the JTable! JTable’s version of getValueAt() will represent its position as seen in the table which may be different… remember it is a window into the model and so could modified on its own.

5. Inserting a row to our model – This is one area I see a lot of new people really struggle with. They have the JTable setup and they didn’t setup a model, so they are then attempting to pass some wicked parameters to some JTable method and jam individual values in where they don’t belong. Our model object makes it really easy to add rows. You need to create an object array, or even a vector if you like, and simply pass it to the addRow() method of model. Here is how it is done for our three columns…

model.addRow(new Object[] {'Martyr', '2', 29});

Done! Any values you don’t specify will be null and left blank when the row is inserted. You still need the commas to show the column is being skipped, but other than that there is nothing to it. So can you see how this might work in something like a button’s actionListener? The listener could read some textfields or checkboxes and build this array dynamically and add it to the model; which in turn updates the JTable. Here is an example of that happening…

// Inline actionListener definition for our button "addbutton"
addbutton.addActionListener(new ActionListener()
{
	  // Button was clicked, perform the action
	  public void actionPerformed(ActionEvent ae)
	  {
			// Add those fields to the model and it will update the JTable.
			model.addRow(new Object[] {txtFirstName.getText(), txtLastName.getText(), selectedAge.getSelectedItem().toString()});

	  }
});

So that is pretty much the basics of the JTable and its model. Once you have practiced with this a bit you can experiment by adding/removing data, setting styles of the JTable (through the JTable’s methods) and move data around (through the model). I recommend you look at the methods of both JTable and DefaultTableModel in the Java documentation and play around with those methods to see what you can build with it. I am sure you will find it a very flexible control with a lot of customization features.

Thanks! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.