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

2019-01-24 21:22发布

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?

2条回答
姐就是有狂的资本
2楼-- · 2019-01-24 21:59

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-24 22:17

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);
查看更多
登录 后发表回答