简体   繁体   English

在Java中剪切,复制和粘贴的最佳方法是什么?

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

I've created an application using Swing with a text area (JTextArea). 我使用带有文本区域的Swing(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? 我该如何实现剪切/复制/粘贴?

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 . 这些都在Swing拖放教程中进行了解释:添加剪切,复制和粘贴 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 基本上,复制到剪贴板使用DefaultToolkit中的StringSelection和ClipBoard

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. 如果复制/粘贴是专门在您的应用程序中,那么您可以实现自己的创建和维护缓冲区的方法,但系统剪贴板方法将是最简单的,因为您不必重新发明轮子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM