1

I want to prevent copying the text from the JTextArea. What is the best approach to do that? I found a KeyListner solution but it didn't seemed best. I don't want to use a key listner for that. Is there a shortcut method/way that I can use?

Community
  • 1
  • 1
Shahrzad
  • 1,062
  • 8
  • 26

2 Answers2

5

Not tested, but I would simply override copy() and cut():

@Override
public void copy() {
    // does nothing
}

@Override
public void cut() {
    // does nothing
}

Looking at the source code, it should work, since that's what JPasswordField does to prevent cutting/copying.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    see answer by (@Azad) rest could be based on [(@camickrs) Key Bindings](http://tips4java.wordpress.com/2008/10/10/key-bindings/) – mKorbel Jul 28 '13 at 11:11
  • This sounds a better idea, since it should also deal with cut / copy invoked via menus ... if that is possible. – Stephen C Jul 28 '13 at 11:12
  • It would also work if the key binding is not Ctrl-C. And it would also prevent copying with the mouse only (which, at least in native apps, is possible under Unix) – JB Nizet Jul 28 '13 at 11:15
  • How `copy()` called when I press Ctrl+c? Is there a keyBinding on JtextArea? – Shahrzad Jul 28 '13 at 11:15
  • then methods implemented in Document(Xxx e.g. Listener) are/could be responsible, better place for JTextComponents – mKorbel Jul 28 '13 at 11:16
  • +1 for that, but need to extend the `JTextArea` class for overriding. thanks any way – Shahrzad Jul 28 '13 at 11:29
4

You can use KeyBindings:

textField.getInputMap().put(KeyStroke.getKeyStroke("control C"), "preventCopy");
textField.getActionMap().put("preventCopy", new AbstractAction(){
     public void actionPerformed(ActionEvent e) {
          //do something else when user presses control+c
      }
});
Azad
  • 5,047
  • 20
  • 38
  • I'm not sure that this would work, as it leaves the original action in place to continue working – MadProgrammer Jul 28 '13 at 11:12
  • 1
    @MadProgrammer: It's working, however, I am totally refuse to prevent CTRL+C from copying, I don't wanna bother the user. – Azad Jul 28 '13 at 11:15
  • 1
    +1 user can also copy the text from menu, anyway new learning for the `keyBinding`, one feature no need to extend `JTextArea`. can you solve my [another problem](http://stackoverflow.com/questions/17652806/arabic-typesetting-font-slowers-my-jtextarea-jtextpane-and-jtexteditor) please. – Shahrzad Jul 28 '13 at 11:31
  • @aquestion [I answered the other problem](http://stackoverflow.com/questions/17652806/arabic-typesetting-font-slowers-my-jtextarea-jtextpane-and-jtexteditor/17908014#17908014), see it. – Azad Jul 28 '13 at 12:15