Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Best way to use a UserObject in JTable

Status
Not open for further replies.

zooxmusic

Programmer
Nov 24, 2004
96
US
Hi all,
I was wondering different people's ways of dealing with a user object in a JTable. Where do you store the user object? Do you make the toString() method one of the fields and just add the object to the first column? Is there a way to add the UserObject to maybe some kind of TableModelAdapter and have it display the columns without having to add the first column like

UserObject uo = new UserObject();

Vector vec = new Vector();
vec.add(uo); // the uo's toString() method
// would return one of the fields
vec.add(uo.getField2());
vec.add(uo.getField3());
etc...
tableModel.addRow(vec);


I don't like this because sometimes I can't say one field is more important than another so to return one on a toString() method makes me think in this manner. I am wondering if there is a way to maybe have an adapter where I would add the uo to it and then add the adapter to the table model and all of the correct methods would be exposed to populate the table. But I am unsure if this is possible and if it is on how to do it.
ie.

UserObjectTableAdapter uota = new UserObjectTableAdapter();
...
uota.add(uo);
tableModel.addRow(uota);

Thanks in advance
Brian


Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
Hi Brian. For increased control over how a table handles your objects, you need to implement the TableModel interface yourself and set an instance of this on your table.

To make implementing TableModel easier, you can instead subclass AbstractTableModel which has much of the necessary functionality conveniently implemented for you.

For examnple, you could have your own addRow method which accepts a UserObject instance, and use the TableModel column handling methods to communicate whatever bits of UserObject make sense for any given column.

Have a look at the source for DefaultTableModel to see how Sun does it to get an understanding of what's involved.

Tim
 
Thanks Tim,
So obvious yet I still didn't see that.

Spend like you don't need the money,
love like you've never been hurt and dance like nobody's watching!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top