使JTable单元格编辑器值可选,但不可编辑?

问题描述:

我试图保持我的 JTable 的严密性和安全性,只允许通过编辑可编辑的列isCellEditable()。但是,我的客户坚持要求他们双击单元格以便他们可以复制其内容,即使它是只读的。我可以让单元格可编辑,而不对它们在 setValueAt()中进行的任何编辑做任何事情(因此当编辑器退出时它会恢复为原始值)。但我不希望这个应用程序感觉如此*。是否有一种简单有效的方法可以将 JTextField 用作单元格编辑器,以允许在编辑器中选择文本,但不可编辑?

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?

我在下面的 JTable 上尝试过这种覆盖,但我认为我不想找到合适的instanceof对象。

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



然而,我的客户坚持要他们双击一个单元格,以便他们可以复制其内容,即使它是只读的。

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.

创建一个使用只读文本字段的自定义编辑器:

Create a custom editor that uses a readonly text field:

JTextField tf = new JTextField();
tf.setEditable(false);
DefaultCellEditor editor = new DefaultCellEditor( tf );
table.setDefaultEditor(Object.class, editor);

使用键盘或鼠标选择要复制的文本。然后,您将使用Ctrl + C复制所选文本。或者你甚至可以在文本字段中添加一个弹出菜单,并添加一个复制菜单项。

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.