0

I've been asked to edit a java desktop application developed by others. I've never worked on Java desktop application before.

There's a JTable and I have to prevent the user from doing CTRL+C and copy the value of a cell. I did it.

The problem is that when the user double clicks a cell and the cursor appears (as you can see from the pic)enter image description here

I'm not able to prevent the user to do CTRL+C. How can I do it?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
MDP
  • 4,177
  • 21
  • 63
  • 119

2 Answers2

3

The problem is that when the user double clicks a cell and the cursor appears

Focus is no longer on the JTable. It is on the editor of the cell which happens to be a JTextField. So you need to remove the copy functionality of the text field.

You do this by removing the Key Binding for the "Control C" on the text field:

DefaultCellEditor editor = (DefaultCellEditor)table.getDefaultEditor(Object.class);
JTextField textField = (JTextField)editor.getComponent();
InputMap im = textField.getInputMap();
im.put(KeyStroke.getKeyStroke("control C"), "none");

You will need to do this for each editor type you have in your table. For example if you have Integer values then you would need to get the editor for the Integer.class and remove its key binding as well.

Note, the same approach can be used for the table, except you use the following InputMap for the table:

InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
camickr
  • 321,443
  • 19
  • 166
  • 288
2

Take away their keyboard!

Okay, that may be problematic. If you don't need the users to edit the table, you could try making the table non-editable. Rather than regurgitate one of many examples on this, I'll leave you this guide on doing it and a StackOverflow question on how to Disable user edit in JTable .

Alternatively, you could look into overriding the keybindings. I've never done that personally, so I leave you a link or two and a StackOverflow question on JTable Key Bindings .

You could also do something clever by accessing the System's Clipboard from java.awt.toolkit. Maybe have it that whenever a user is editing a cell, their clipboard is set to an empty string or (if you don't want to screw over people editing cells but not trying to copy them) you could combine that with the keybindings so they think they're copying data but they end up pasting "Sorry. Copying is not allowed in this application."

Hope something here works.

CasualViking
  • 262
  • 1
  • 9