Reputation: 5574
I've created an application using Swing with a text area (JTextArea). I want to create an "edit" menu, with options to cut and copy text from the text area, and paste text from the clipboard into the text area.
I've seen a couple of ways to do this, but I wanted to know what the best way is. How should I implement the cut/copy/paste?
Upvotes: 4
Views: 14939
Reputation: 36601
I would personally opt for re-using the standard cut, copy and paste actions. This is all explained in the Swing drag-and-drop tutorial: adding cut, copy and paste. The section about text components is the most relevant for you. A quick copy-paste of some code of that page:
menuItem = new JMenuItem(new DefaultEditorKit.CopyAction());
menuItem.setText("Copy");
menuItem.setMnemonic(KeyEvent.VK_C);
Upvotes: 15
Reputation: 1966
Basically the copy to clipboard uses the StringSelection and ClipBoard from DefaultToolkit
StringSelection ss = new StringSelection(textarea.getText());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,this);
and
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(this);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String text = (String)t.getTransferData(DataFlavor.stringFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
As Andrew pointed out, you can tell which are the other ways you have seen. If you are looking for cut/copy/paste from/to your application and other applications then you must have to use the System Clipboard. If the copy/paste is specifically inside your application then you can implement your own ways of creating and maintaining a buffer, but the system clipboard method will be the easiest since you don't have to reinvent the wheel.
Upvotes: 5