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

蓝咒 提交于 2019-11-27 22:51:35

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/9123358/what-is-the-best-way-to-cut-copy-and-paste-in-java

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