在JTable中拖放行,可以通过实现自定义的TransferHandler和DragGestureListener来实现。以下是一个简单的示例:
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
public class RowTransferHandler extends TransferHandler {
private JTable table;
public RowTransferHandler(JTable table) {
this.table = table;
}
@Override
protected Transferable createTransferable(JComponent c) {
JTable table = (JTable) c;
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
Object value = table.getValueAt(row, col);
return new StringSelection(value.toString());
}
@Override
public boolean canImport(TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.stringFlavor);
}
@Override
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
JTable.DropLocation dl = (JTable.DropLocation) support.getDropLocation();
int row = dl.getRow();
int col = dl.getColumn();
int max = table.getModel().getRowCount();
if (row < 0 || row > max) {
return false;
}
try {
String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
table.getModel().setValueAt(data, row, col);
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.*;
public class RowDragGestureListener implements DragGestureListener {
private JTable table;
public RowDragGestureListener(JTable table) {
this.table = table;
}
@Override
public void dragGestureRecognized(DragGestureEvent dge) {
Point clickPoint = dge.getDragOrigin();
int row = table.rowAtPoint(clickPoint);
table.getSelectionModel().setSelectionInterval(row, row);
Transferable transferable = new StringSelection("");
dge.startDrag(DragSource.DefaultMoveDrop, transferable, new RowDragSourceListener(table));
}
}
JTable table = new JTable();
table.setDragEnabled(true);
table.setTransferHandler(new RowTransferHandler(table));
table.getColumnModel().getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(table, DnDConstants.ACTION_MOVE, new RowDragGestureListener(table));
这样,就可以在JTable中实现行的拖放操作了。
领取专属 10元无门槛券
手把手带您无忧上云