JTableのCellEditorを編集不可だが選択・コピーを可能に変更する
Total: 5055, Today: 1, Yesterday: 6
Posted by aterai at
Last-modified:
Summary
JTableのCellEditorとして編集不可・選択コピー可能なJTextFieldを設定します。
Screenshot

Advertisement
Source Code Examples
JTable table = new JTable(model);
table.setAutoCreateRowSorter(true);
table.setFillsViewportHeight(true);
// table.setFocusable(false);
// table.setCellSelectionEnabled(false);
table.setSelectionForeground(Color.BLACK);
table.setSelectionBackground(new Color(0xEE_EE_EE));
JTextField field = new JTextField();
field.setEditable(false);
field.setBackground(table.getSelectionBackground());
field.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
field.setComponentPopupMenu(new TextComponentPopupMenu());
DefaultCellEditor cellEditor = new DefaultCellEditor(field);
cellEditor.setClickCountToStart(1);
table.setDefaultEditor(Object.class, cellEditor);
View in GitHub: Java, KotlinDescription
JTable#isCellEditable(...)などをオーバーライドしてJTableを編集不可にするとセル内の文字列を部分選択してコピーできない- デフォルトの
JTableではセルを選択してCtrl+Cを入力しても列がタブ区切りでコピーされる Object.classのDefaultCellEditorとして編集を不可にしたJTextFieldを設定することで編集は不可だが、文字列を選択してのコピーは可能にするJTextField#setEditable(false)で編集不可に設定JTextField#setBackground(JTable#getSelectionBackground())でセルエディタの背景色をJTableの選択時背景色と同じに変更JTextField#setComponentPopupMenu(...)でJPopupMenuを設定し、ポップアップメニューからのコピーも可能にするDefaultCellEditor#setClickCountToStart(1)を使用してシングルクリックでセルエディタが起動するよう設定し直接文字列の選択を可能にする