Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow user to copy, cut & paste selected words from a JTextArea?

Say I have created a GUI with its main pannel a JTextArea and a menubar above (which contains copy and paste button, shortcutted by ctrl+c and ctrl+v).

Supposibly after some working the program will spit out a bunch of data onto the JTextArea, and then I want to allow the user to copy, cut or paste selected(highlighted) words from the JTextArea to other places like a notepad or etc.

So what kind of listener should I use to sense the selection, get the selected words out and put them into the place where the OS stores copied stuff? Plz be specific, thanks a lot for any help! :)

like image 297
Allen Ai Avatar asked Dec 08 '22 21:12

Allen Ai


2 Answers

The OS shortcuts for cut, copy and paste work by default in JTextArea.

However, JTextArea extends JTextComponent which has cut(), copy() and paste() methods that you can call in case you want to add custom actions (line context-menu or top menu items or toolbar buttons) for these operations.

like image 80
Dan D. Avatar answered Dec 11 '22 11:12

Dan D.


To add to Dan's reply, JTextArea does provide cut(), copy() and paste() methods that will handle the actual OS specific actions for your.

roseindia.net has some code for reference.

There are other ways to copy as well which are doucmented in similar stack overflow threads such as this one :)

like image 43
javatarz Avatar answered Dec 11 '22 10:12

javatarz