I have tried to keep my JTable
's tight and secure, making only editable columns editable via isCellEditable()
. However, my clients are insisting that they want to double click on a cell so they can copy its contents, even if it is read only. I could let the cell be editable and not do anything with any edits they could make in the setValueAt()
(so it reverts back to original value when editor exits). But I don't want this application to feel so freeform. Is there an easy effective way to make the JTextField
used as the cell editor to allow selecting of text in the editor, but not editable?
I tried this override on my JTable
below, but I don't think I'm looking for the right "instanceof" object.
@Override
public TableCellEditor getDefaultEditor(Class<?> columnClass) {
if (super.getDefaultEditor(columnClass) instanceof JTextField) {
JTextField jTextField = new JTextField();
jTextField.setEditable(false);
return (TableCellEditor) jTextField;
}
if (columnClass == null) {
return null;
}
else {
Object editor = defaultEditorsByColumnClass.get(columnClass);
if (editor != null) {
return (TableCellEditor)editor;
}
else {
return getDefaultEditor(columnClass.getSuperclass());
}
}
}
You could just use a
MouseListener
, and on a double click, programmatically copy the contents of the cell to the clipboard. Something like:Here's a full example:
Create a custom editor that uses a readonly text field:
Use the keyboard or mouse to select the text you want to copy. Then you would then use Ctrl+C to copy the selected text. Or you could even add a popup menu to the text field and add a
Copy
menu item.