Monday, August 3, 2009

Using Arbitrary Objects as JTable Data

While we normally supply Strings, JTable can actually accept any arbitrary objects as data. To display the data, its toString() method is called for a string that the JTable can display.

If the data is not of the supported type, then its toString() method must be implemented to return something for JTable to display intelligibly. For example, given a class called ArbitraryObject as follows:

public class ArbitraryObject
private String name;

public ArbitraryObject(String name)
{ = name;

public String toString()
return "The number is " + name; // prepend "The number is" to name
Then you can create a JTable initialized with instances of ArbitraryObject as data:

private ArbitraryObject[][] data =
{ {new ArbitraryObject("1"), new ArbitraryObject("1"), new ArbitraryObject("1")},
{new ArbitraryObject("2"), new ArbitraryObject("2"), new ArbitraryObject("2")},
{new ArbitraryObject("3"), new ArbitraryObject("3"), new ArbitraryObject("3")},
{new ArbitraryObject("4"), new ArbitraryObject("4"), new ArbitraryObject("4")},
{new ArbitraryObject("5"), new ArbitraryObject("5"), new ArbitraryObject("5")},
{new ArbitraryObject("6"), new ArbitraryObject("6"), new ArbitraryObject("6")} };
private String[] headerLabels = { "Column One", "Column Two", "Column Three" }

JTable table = new JTable(data, headerLabels);
add(table, BorderLayout.CENTER);
Here's the screenshot of this JTable:

The utility of this is that you can easily associate each cell in the JTable with an object it represents. JTable "displays" the object with the value returned by the object's toString(). For example, if you select a cell based on what's displayed in it, a listener registered for the JTable can easily retrieve its associated object using getValueAt(row, col) without going through convolutions to look it up. Think of it as a link from the table back to the data it represents:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener()
ublic void valueChanged(ListSelectionEvent event)
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
ArbitraryObject o = table.getValueAt(row, col);

No comments:

Post a Comment