Can I cut, copy, and paste between AWT and other X applications under Linux?

Nathan Meyers

Yes - sometimes it's easy, and sometimes not. X has two commonly used mechanisms for copying and pasting between applications, which can be a bit confusing:

  • The primary selection: this is typically text that is selected for copying by dragging the cursor, then copied to other applications by clicking the middle mouse button. Most X applications support primary selection.
  • The clipboard: this mechanism works much like the Windows clipboard - applications can cut/copy/paste text using menu selections and common key shortcuts such as ^C for copy, ^X for cut, and ^V for paste. The clipboard is supported by some X applications, but many apps do not support it.

The AWT supports the clipboard but not primary selection - probably because the clipboard is a common mechanism on most systems and primary selection is not.

The AWT's support of the clipboard consists of two pieces:

  • Objects that can interact with the clipboard already do: JTextArea, for example, has copy(), cut(), and paste() methods that will transfer text between itself and the clipboard.
  • Any object can use the classes in java.awt.datatransfer to interact directly with the clipboard.

Things are not so easy if you want to use the primary selection mechanism - you'll need to add your own JNI code to make the necessary X calls to use it.