[英]Is it possible to disable drag and drop for specific cell in JTable?
我正在嘗試將單元格拖放到Jtable
。 它可以工作,但是現在我想知道是否可以僅對第一個單元格禁用拖放操作,例如,因為我不想修改此單元格?
這是代碼
public class Test extends JFrame {
public Test() {
setSize(500, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pan = new JPanel();
pan.setLayout(new GridLayout(1, 1, 5, 5));
Object[][] data = new Object[][] { { "00", "10", null }, { "01", "11", null }, { "02", "20", null } };
String[] name = new String[] { "a", "b", "c" };
DefaultTableModel model = new DefaultTableModel(data, name);
JTable jt = new JTable(model);
pan.add(jt);
jt.setRowHeight(24);
jt.setRowSelectionAllowed(false);
jt.setFillsViewportHeight(true);
jt.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jt.setDragEnabled(true);
jt.setDropMode(DropMode.USE_SELECTION);
jt.setTransferHandler(new MyTransferHandlerT());
setContentPane(pan);
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
和TransferHandler
的代碼
public class MyTransferHandlerT extends TransferHandler {
private JTable table;
private DefaultTableModel model;
private int rowIndex;
private int colIndex;
@Override
public int getSourceActions(JComponent c) {
return MOVE;
}
@Override
protected Transferable createTransferable(JComponent source) {
table= (JTable)source;
model = (DefaultTableModel) table.getModel();
rowIndex = table.getSelectedRow();
colIndex = table.getSelectedColumn();
model.getValueAt(rowIndex, colIndex);
String value = (String)model.getValueAt(rowIndex, colIndex);
Transferable t = new StringSelection(value);
return t;
}
@Override
protected void exportDone(JComponent source, Transferable data, int action) {
table= (JTable)source;
model = (DefaultTableModel) table.getModel();
rowIndex = table.getSelectedRow();
colIndex = table.getSelectedColumn();
model.setValueAt("", rowIndex, colIndex);
}
@Override
public boolean canImport(TransferSupport support) {
if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
return true;
}
@Override
public boolean importData(TransferSupport support) {
table = (JTable) support.getComponent();
Object data= null;
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
try {
data = (Object) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException e) {
System.out.println("unsupported Flavor Exception");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO Exception");
e.printStackTrace();
}
model.setValueAt(data, row, col);
model.fireTableStructureChanged();
return false;
}
}
謝謝。
model.setValueAt(data, row, col);
//model.fireTableStructureChanged();
不要直接調用fireTableStructureChanged()方法。 那是TableModel的責任。
是否可以僅對第一個單元格禁用拖放
請參閱Swing教程中有關位置敏感下降的部分 。 它有一個示例,該示例將禁用在第一列上的放置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.