1 回答
TA贡献1830条经验 获得超3个赞
为了实现此行为,您可以使用 aMouseListener
和 a的组合MouseMotionListener
。DefaultTableModel
提供的功能可用于将Point
事件的行转换为事件发生的行。使用此功能,我们可以有效地拖动表格行。下面的代码示例显示了实时拖动表格行的基本实现。请注意,table
和tableModel
属性被故意弱化:我们不希望MouseHandler
保留对 或table
的强引用tableModel
。
public class MouseHandler implements MouseListener, MouseMotionListener {
private Integer row = null;
private final WeakReference<JTable> table;
private final WeakReference<DefaultTableModel> tableModel;
public MouseHandler(JTable table, DefaultTableModel model) {
this.table = new WeakReference<>(table);
this.tableModel = new WeakReference<>(model);
}
@Override
public void mouseClicked(MouseEvent event) {}
@Override
public void mousePressed(MouseEvent event) {
JTable table;
if((table = this.table.get()) == null) {
return;
}
int viewRowIndex = table.rowAtPoint(event.getPoint());
row = table.convertRowIndexToModel(viewRowIndex);
}
@Override
public void mouseReleased(MouseEvent event) {
row = null;
}
@Override
public void mouseEntered(MouseEvent event) {}
@Override
public void mouseExited(MouseEvent event) {}
@Override
public void mouseDragged(MouseEvent event) {
JTable table;
DefaultTableModel tableModel;
if((table = this.table.get()) == null || (tableModel = this.tableModel.get()) == null) {
return;
}
int viewRowIndex = table.rowAtPoint(event.getPoint());
int currentRow = table.convertRowIndexToModel(viewRowIndex);
if(row == null || currentRow == row) {
return;
}
tableModel.moveRow(row, row, currentRow);
row = currentRow;
table.setRowSelectionInterval(viewRowIndex, viewRowIndex);
}
@Override
public void mouseMoved(MouseEvent event) {}
}
在我看来,这是一个比大多数使用 的建议更干净、更友好的实现TransferHandler
。
添加回答
举报