File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

Sorting JTable

sparks
Greenhorn

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 > t.gd) || (points == t.points) && (gd > t.gd) && (goalsFor > t.goalsFor)
{
result -1
}
else
{
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
author
Ranch Hand

Joined: May 14, 2003
Posts: 762
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.
-Jeff-
[ March 25, 2004: Message edited by: Jeff Langr ]

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

Joined: Dec 10, 2001
Posts: 7023
sparks,
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: http://aspose.com/file-tools
 
subject: Sorting JTable