Instead of using vectors to fill your table, you can use a more sophisticated table model implementation that allows you to work directly with File
objects as rows in your table. I'm talking about either DataObjectTableModel or Rob Camick's RowTableModel.
So, let's say you have the table model implementation solved and each row in your table is a File
object. Now, I wouldn't make any cell editable and let the table just display files info, considering:
- There are many factors that can go wrong (i.e: invalid or existent file name)
- It's not a
TableModel
responsibility to reflect the update in the HD.
- It can be done using
TableModelListener
but the events are fired once the model has changed, so if you have troubles updating the file name in the HD then you have to revert the table model's changes. Not so easy though.
In order to re-name a file, I'd attach a MouseListener to the table and show a pop up dialog to let the user input the new file name. Finally use the File
API to rename the file and update the table model reflecting these changes.
Snippet
final DataObjectTableModel<File> model = new DataObjectTableModel<File>(header) {
// Override getValueAt() and getColumnClass() here
};
final JTable table = new JTable(model);
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() >= 2 && !e.isPopupTrigger()) {
int selectedRow = table.rowAtPoint(e.getPoint());
if (selectedRow != -1) {
String newName = JOptionPane.showInputDialog (
null
, "Please input the new name"
, "Rename file"
, JOptionPane.INFORMATION_MESSAGE
);
if (newName != null) {
int modelIndex = table.convertRowIndexToModel(selectedRow);
File file = model.getDataObject(modelIndex);
// Maybe this part should be done
// using a SwingWorker to avoid blocking the EDT
String newPath = file.getParent() + File.separator + newName;
File newFile = new File(newPath);
if (file.renameTo(newFile)) {
model.deleteDataObject(modelIndex); // remove the old file
model.insertDataObject(newFile, modelIndex); // insert the new file in the same index
} else {
JOptionPane.showMessageDialog (
null
, "An error happened trying to rename file " + file.getName()
, "Error!"
, JOptionPane.WARNING_MESSAGE
);
}
}
} // if (selectedRow != -1)
} // if (e.getClickCount() >= 2 && !e.isPopupTrigger())
}
});