在表模型(而不是外部数组)上使用冒泡排序的唯一原因是我们可以通过查看表来观察排序过程。
因此,请使用DefaultTableModel
的setValueAt
和getValueAt
方法进行比较和切换。 这里是一个例子。
class DTMSlowSorter {
/**
*/
private DefaultTableModel model;
/**
* the number of the column by which we want to sort
*/
private int sortColNum;
/**
* the comparator for the elements.
*/
private Comparator comparator;
/**
* The time to sleep between two sorting steps.
*/
private int sleepTime = 500;
/**
* swaps the contents of two rows.
*/
void swap(final int rowA, final int rowB) {
try {
EventQueue.invokeAndWait(new Runnable(){public void run() {
int colCount = model.getColumnCount();
Object[] temp = new Object[colCount];
for(int i = 0; i < colCount; i++) {
temp[i] = model.getValueAt(rowA, i);
}
for(int i = 0; i < colCount; i++) {
model.setValueAt(model.getValueAt(rowB, i), rowA, i);
}
for(int i = 0; i < colCount; i++) {
model.setValueAt(temp[i], rowA, i);
}
}});
Thread.sleep(sleepTime);
} catch(InterruptedException ex) { ex.printStackTrace();}
}
/**
* compares two rows.
* @returns
* -1 if A < B
* 0 if A = B
* 1 if A > B
*/
int compare(int rowA, int rowB) {
Object valA = model.getValueAt(rowA, sortColNum);
Object valB = model.getValueAt(rowB, sortColNum);
if(comparator != null) {
return comparator.compare(valA, valB);
}
else {
return ((comparable)valA).compareTo(valB);
}
}
public void sort() {
// here your bubblesort implementation, using compare and swap.
}
}
(我希望我没有做你的整个家庭作业在这里,但至少你必须实现自己的排序。)
傻点在这里,但如果你必须使用一个冒泡排序,那么你不会追求速度,那么为什么要寻找更快的方式?你的计划听起来不错。目标是排序气泡,所以排序气泡。如果你必须轨道冥王星去做,那又怎么样? – stu 2011-04-05 20:53:00
看到这个例子http://www.exampledepot.com/egs/javax.swing.table/SortCol.html – 2011-04-05 20:55:23
@camickr这个网站是关于学习和帮助他人,不积累声望点。 – 2011-04-05 21:14:57