在開發小型任務管理器時,我注意到列未正確排序。爲了拋棄我的程序中的問題,我創建了一個最小版本,但它仍然無法對唯一列進行排序。setAutoCreateRowSorter在更新後沒有正確排序表列
import java.awt.BorderLayout;
import java.util.List;
import java.util.Random;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
public class TableSortTest extends JFrame
{
private final JTable table;
private final ATableModel model;
public TableSortTest()
{
setDefaultCloseOperation (EXIT_ON_CLOSE);
setSize (1366, 768);
setLocationRelativeTo (null);
model = new ATableModel();
table = new JTable();
table.setFillsViewportHeight (true);
table.setAutoCreateRowSorter (true);
table.setModel (model);
add (new JScrollPane (table), BorderLayout.CENTER);
setVisible (true);
Worker worker = new Worker();
worker.execute();
}
private class Pair
{
int index;
int value;
}
private class Worker extends SwingWorker <Void, Pair>
{
@Override
protected Void doInBackground()
{
while (!isCancelled())
{
Random r = new Random();
for (int i = 0; i < 100; i++)
{
int indice = getIndexInRange (0, 99);
Pair p = new Pair();
p.index = indice;
p.value = Math.abs (r.nextInt());
publish (p);
}
try
{
Thread.sleep (1000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
@Override
public void process (List <Pair> items)
{
for (Pair p : items)
{
model.setValueAt (p.value, p.index, 0);
}
}
}
public static int getIndexInRange (int min, int max)
{
return (min + (int) (Math.random() * ((max - min) + 1)));
}
private class ATableModel extends AbstractTableModel
{
private final Integer [] data;
public ATableModel()
{
data = new Integer [100];
Random r = new Random();
for (int i = 0; i < 100; i++)
{
data [i] = Math.abs (r.nextInt());
}
}
@Override
public int getColumnCount()
{
return 1;
}
@Override
public int getRowCount()
{
return data.length;
}
@Override
public Object getValueAt (int rowIndex, int columnIndex)
{
return data [rowIndex];
}
@Override
public void setValueAt (Object value, int rowIndex, int columnIndex)
{
data [rowIndex] = (Integer) value;
fireTableRowUpdated (rowIndex, columnIndex);
}
@Override
public Class getColumnClass (int columnIndex)
{
return Integer.class;
}
@Override
public String getColumnName (int col)
{
return "Column";
}
}
public static final void main (String [] args)
{
SwingUtilities.invokeLater (() ->
{
try
{
new TableSortTest();
}
catch (Exception e)
{
e.printStackTrace();
}
});
}
}
我試圖用ScheduledExecutorService
+ Runnable
和Timer
+ TimerTask
只是爲了測試,如果它是一個線程的問題,但行爲是一樣的。我還閱讀了有關該主題的Java教程頁面。鑑於我的表只使用標準類型,我認爲一個簡單的table.setAutoCreateRowSorter (true);
應該完成這項工作,不是嗎?
不應該在每次修改/添加/刪除之後對錶進行排序,甚至會被解僱嗎?
'setSortsOnUpdates(true)'在這種情況下可能是最優的;我會避免'KeyListener'。 – trashgod