Reputation: 53
I have a JTable and I added a DefaultTabelModel to it. I created a popup menu that appears when users right click on a cell in the table. One of the items in the menu is "Rename." How can I make the selected cell editable when the Rename item is clicked? I have set up all the elements and the only missing piece here is making THE selected cell editable.
The isCellEditable(row, col)
method in the DefaultTableModel is not helpful here because it sets a cell's editability based on its position (i.e. row and column) in the table, not the selection status of a cell.
I suspect that I will need TableCellEditor, but I am not sure how to use it. I would really appreciate a sample code on how to make this happen and/or explanations of how to use TableCellEditor for this purpose. Thank you in advance!!
Relevant pieces of my code:
class DataListTable extends JTable
mouseReleased():
int row = this.getSelectedRow();
popupmenu.show(this, event.getX(), event.getY());
class RenameDataMenuItem
actionPerformed():
//want to get the (row, col) of the selected cell here and make it editable
Upvotes: 1
Views: 899
Reputation: 324197
How can I make the selected cell editable when the Rename item is clicked?
The isCellEditable(...)
method will determine if the cell can be edited via the table editor.
You can still change the data in the model by using the setValueAt(..)
method of the JTable
or the TableModel
.
So what you can do is in your rename menu item you can display a JOptionPane
to prompt for the new value. Then you just manually save the value using either of the above methods.
Upvotes: 1
Reputation: 381
Try something along the lines of this:
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
JComponent component = new JTextField();
@Override
public Object getCellEditorValue() {
return ((JTextField)component).getText();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if(isSelected) {
((JTextField)component).setText((String)value);
}
return component;
}
}
Upvotes: 0