views:

918

answers:

3

I have a JTable that I want to use to display some data (a String and a Boolean in each row). The data is maintained by my own class. Is there some way to bind the data model to the JTable, so that when I add to the model, the JTable is dynamically updated and when I remove something from the model, the row is removed from the JTable?

I have previously worked with Flex and Actionscript, and this is very easy to do there with data binding, so I'm just wondering how it's done in Java.

Thanks.

+1  A: 

You will need to have your dataset implement the TableModel interface. if you do that then you can apply it to the JTable. If you extend AbstractTableModel you will inherit some event firing methods that your table will handle and will update the view. see this tutorial. Note that the default implementation of JTable will renderer your data for you, and if a Boolean is found, it will show up as a check box.

akf
Thanks...when I looked at this example before, I only thought it worked for when the user edits data in the table. I didnt think about making my data model implement TableModel itself.
knt
+3  A: 

You'll probably find both the Java JTable tutorial and the JTable API documentation helpful in understanding how JTable works, but otherwise here's a quick rundown.

The premise of a JTable is that it is paired with an object that implements the TableModel interface, which by default is an instance of DefaultTableModel. The table model object is made up of a list of columns, each of which has its own data type (String and Boolean in your case), and a list of rows containing the actual data for the table.

Whenever the JTable is drawn by the swing drawing code, it repeatedly calls the method:

public Object getValueAt(int row, int col)

Thus, when you add data to the table model, it is always rendered as you expect in the next screen refresh (dynamically).

The only thing you really need to worry about, then, is getting the data from your object into the table model and back out again. Other than that, JTable takes care off all the heavy lifting.

Peter Nix
+1  A: 

While implementing TableModel is easy enough for simple cases, you might want to consider a true binding approach (my favorite is Glazed Lists - watch the 30 second video on how easy this is and you'll be won over). Beans Binding (now Better Beans Binding) also has an implementation of observable lists that might be useful (although I much prefer the Glazed Lists approach)

Kevin Day