我正在尝试拖放我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;
}
}
感谢。
答案 0 :(得分:0)
model.setValueAt(data, row, col);
//model.fireTableStructureChanged();
不要直接调用fireTableStructureChanged()方法。这是TableModel的责任。
是否可以仅为第一个单元格禁用拖放
请参阅Location Sensitive Drop上的Swing教程中的部分。它有一个示例将禁用第一列的删除。