import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;class Win extends Frame 
implements ActionListener {
private static final long serialVersionUID = 1L;
MenuBar menubar;
Menu menu;
MenuItem copy, cut, paste;
TextArea text1, text2;
Clipboard clipboard = null;

Win() {
clipboard = getToolkit().getSystemClipboard(); //获得系统剪贴板
menubar = new MenuBar();
menu = new Menu("Edit");
copy = new MenuItem("copy");
cut = new MenuItem("cut");
paste = new MenuItem("paste");
text1 = new TextArea(10, 20);
text2 = new TextArea(10, 20);
copy.addActionListener(this);
cut.addActionListener(this);
paste.addActionListener(this);
setLayout(new FlowLayout());
menubar.add(menu);
menu.add(copy);
menu.add(cut);
menu.add(paste);
setMenuBar(menubar);
add(text1);
add(text2);
setBounds(100, 100, 400, 345);
setVisible(true);
validate();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
} @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == copy) {
String temp = text1.getSelectedText();
StringSelection text = new StringSelection(temp);
clipboard.setContents(text, null);
}
else if (e.getSource() == cut) {
String temp = text1.getSelectedText();
StringSelection text = new StringSelection(temp);
clipboard.setContents(text, null);
int start = text1.getSelectionStart();
int end = text1.getSelectionEnd();
text1.replaceRange("", start, end);
}
else if (e.getSource() == paste) {
Transferable contents = clipboard.getContents(this);
DataFlavor flavor = DataFlavor.stringFlavor;
if (contents.isDataFlavorSupported(flavor)) {
try {
String str = (String)contents.getTransferData(flavor);
text2.append(str);
}
catch (Exception ee) {
}
}
}
}
}public class Example7_11 {
    public static void main(String args[]) {
     new Win();
    }
}

解决方案 »

  1.   


            else if (e.getSource() == paste) {
                Transferable contents = clipboard.getContents(this);
                DataFlavor flavor = DataFlavor.stringFlavor;//获得Java Unicode String 类型的DataFlavor
                if (contents.isDataFlavorSupported(flavor)) {
                    try {
                        String str = (String)contents.getTransferData(flavor);
                        text2.append(str);
                    }
                    catch (Exception ee) {
                    }
                }
            }
    JDK中的解释:DataFlavor 提供有关数据的元信息。DataFlavor 通常用于访问剪切板上的数据,或者在执行拖放操作时使用。
    那么这段代码就可以理解成:在触发“粘贴”操作时,实例化一个DataFlavor用来读取剪贴板上的内容
      

  2.   

    Falvor 意为 风味,味道
    个人感觉DataFlavor有点数据类型的意思