Two Laptop Bag
The moose likes Beginning Java and the fly likes Sorting JTable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting JTable" Watch "Sorting JTable" New topic

Sorting JTable


Joined: Mar 25, 2004
Posts: 1
Hi all (first post)
I have created a small program that acts as a simple football league buti am having difficulty sorting the JTable where the teams are displayed.
I have two classes:
1. Input - Enters result and displays a list of results entered
2. Output - Displays a league table where team data is stored (i.e. Team name, games won/drawn/lost, goals for/against, goal difference, points)
I have some code to sort the table but am unsure if it is correct and where it should be placed. I know collections.sort(table); can be used with a bunch of if statements:
int result;
if (points > t.points) || (points == t.points) && (gd > || (points == t.points) && (gd > && (goalsFor > t.goalsFor)
result -1
result 1
return result
I know this needs more work but where this is to be placed is confusing.
Any help would be grateful, thanks
Jeff Langr
Ranch Hand

Joined: May 14, 2003
Posts: 799
Welcome to JavaRanch. Just FYI, the moderators will ask you to supply a real first and last name.
First have your Team class implement the Comparable interface. This means supplying a compareTo method that does the job of your long "if" expression (I expressed the same condition differently):

Then in your AbstractTableModel subclass, implement a sort method you can call:

If you want to get more complex and allow sorting by different columns based on what the user clicks, you can create classes that implement the interface java.util.Comparator (q.v.).
You should start by looking at the API documentation for the Comparable interface. Then take a look at the sort methods in the Collections class.
[ March 25, 2004: Message edited by: Jeff Langr ]

Books: Pragmatic Unit Testing in Java, Agile Java, Modern C++ Programming with TDD, Essential Java Style, Agile in a Flash. Contributor, Clean Code.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Sorting JTable
It's not a secret anymore!