简体   繁体   中英

Set Jtable cell editable ONLY upon selection

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 (ie 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

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.

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;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM