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

妖精的绣舞 提交于 2019-11-29 05:14:21
Robin

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);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!