0

Is it possible to sort/order the contents of a jTable before committing to a bound Java DB?

4

1 回答 1

0

您也可以在 java 代码中执行此操作,我假设您使用 aDefaultTableModel作为您的模型JTable

首先从模型中获取数据,如下所示:

JTable grid =  new JTable(); //your grid to be persisted
DefaultTableModel model = grid.getModel(); //get the model (DefaultTableModel)
Vector vectorData = model.getDataVector(); //the data (Vector of vectors)

然后使用传递你的sort()方法来实现:java.util.CollectionsComparator

 public static final Comparator<Vector> COMPARATOR_BY_KEY = new Comparator<Vector>() {
    public int compare(Vector o1, Vector o2) {
        //Get the Column to be used as criteria for sorting
        //Need to be casted (cast to your real data type) as this is a Vector of Vectors 
        //In this example I'm assuming that cell data type is `String`
        String elementAtCell1 = (String) o1.elementAt(0); 
        String elementAtCell2 = (String) o2.elementAt(0);
        return elementAtCell1.compareTo(elementAtCell2);
    }
 };

这是我要从 model.getDataVector() 中检索的模拟数据;

 Vector vector = new Vector() {
        {
            add(new Vector() {
                {
                    add("KEYA");
                    add(100);
                    add(1.1);
                }
            });
            add(new Vector() {
                {
                    add("KEYC");
                    add(11);
                    add(2.2);
                }
            });
        }
  };

因此,在将数据发送到持久层之前,您可以这样称呼它:

Collections.sort(vectorData, COMPARATOR_BY_KEY);
于 2013-11-22T21:28:12.283 回答