在表模型(而不是外部數組)上使用冒泡排序的唯一原因是我們可以通過查看錶來觀察排序過程。
因此,請使用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