What is the best way to cut, copy and paste in Java?

I created an application using Swing with a text area (JTextArea). I want to create an β€œedit” menu, with the ability to cut and copy text from the text area and paste the text from the clipboard into the text area.

I saw a couple of ways to do this, but I wanted to know what was the best way. How do I cut / copy / paste?

+3
source share
2 answers

I personally would prefer reusing standard cut, copy and paste actions. All of this is explained in Swing drag-and-drop: adding cut, copy and paste . The section on text components is most relevant to you. A quick copy of the mouth of some code on this page:

menuItem = new JMenuItem(new DefaultEditorKit.CopyAction()); menuItem.setText("Copy"); menuItem.setMnemonic(KeyEvent.VK_C); 
+14
source

Most copy to clipboard uses 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 Andrey noted, you can find out which of them you saw. If you are looking to cut / copy / paste from / to the application and other applications, you need to use the system clipboard. If copy / paste is specially located inside your application, you can implement your own ways to create and maintain a clipboard, but the system clipboard method will be the easiest, since you do not need to reinvent the wheel.

+5
source

Source: https://habr.com/ru/post/1433212/


All Articles