Hey all,
I wrote the following code for a JTable and I'm trying to use a table sorter to sort the first column content alphabetically, for now. Later, I'd like to use the third column and sort the table's rows based on ascending dates.
For some reason, my comparator is not being called at all and I'm not sure what I'm doing wrong. I'm using JDK 6, which allows me to use a TableRowSorter. It is the first time I'm using this, so I may not know how to use it correctly. Does anybody have any idea what I'm doing wrong?
Please advice.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Comparator;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class MyTable {
JTable table;
public MyTable() {
JFrame frame = new JFrame("My Table");
JPanel panel = new JPanel(new BorderLayout());
table = createTable();
panel.add(table.getTableHeader(), BorderLayout.NORTH);
panel.add(table);
frame.getContentPane().add(panel);
frame.setSize(new Dimension(400,150));
frame.setVisible(true);
}
private JTable createTable()
{
Object [][] data = {{"Nazli", "Shahi", "Wed, Mar 31, 1982"},{"Nima", "Sohrabi", "Thu, Jul 15, 1982"},
{"Farsheed", "Tari", "Mon, Jun 13, 1967"}, {"Anousheh", "Modaressi", "Tue, Sep 18, 1964"}};
String [] columnNames = {"First Name","Last Name","DOB"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
TableRowSorter sorter = new TableRowSorter(model);
sorter.setComparator(0, new MyComparator());
table.setRowSorter(sorter);
return table;
}
private class MyComparator implements Comparator {
public int compare(Object s1, Object s2) {
String first = s1.toString();
String second = s2.toString();
System.err.println("returning "+(first.substring(0, 1)).compareTo(second.substring(0, 1)));
return (first.substring(0, 1)).compareTo(second.substring(0, 1));
}
}
public static void main(String[] args) {
MyTable test = new MyTable();
}
}