模拟实现notepad的复制粘贴功能,但是总搞不好,也上网查了些
不过小弟能力有限,请各位哥哥指点指点看看哪里错了?
String s;
Clipboard clip=new Clipboard("clip1");
Transferable to_clip;
Transferable from_clip;
......
if(ae.getSource()==copy){
s=note.ta.getSelectedText();
System.out.println(s);
if(s!=null){
System.out.print("不为空"+s);
to_clip=new StringSelection(s);
clip.setContents(to_clip,null);
System.out.println(clip.toString());
}
else if(ae.getSource()==paste){
from_clip=clip.getContents(this);
if(from_clip==null){
System.out.println(s);
//if(from_clip.isDataFlavorSupported(DataFlavor.stringFlavor))
//上面这一行我已经加了//如果不加,那报错就是在上面这一行
{
try {
s=(String) from_clip.getTransferData(DataFlavor.stringFlavor);
//执行后老是报错,提示是在上面这一行 java.lang.NullPointerException
System.out.println(s);
} catch (UnsupportedFlavorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int i=note.ta.getSelectionEnd();
note.ta.insert(s,i);
//}
}

}//

解决方案 »

  1.   

    if(from_clip==null)
    如果上面这行我改为
    if(from_clip!=null)
    那么当我点击粘贴的时候,什么反映也没有,也不报错
    哥哥们 给指点指点
      

  2.   

    Clipboard clip=Toolkit.getDefaultToolkit().getSystemClipboard(); 
      

  3.   

    申明一点我是这样建立的:Clipboard clip=new Clipboard();//当我用Toolkit.getDefaultToolkit().getSystemClipboard()的时候就正常了,功能基本实现了,为什么会这样呢
    else if(ae.getSource()==paste){
    from_clip=clip.getContents(this);
    if(from_clip==null){
    System.out.println("before from_clip=clip.getContents(this);");}我在paste按钮的代码里面加了这一段
    而输出语句始终不执行,说明上面from_clip是null的;但是在下面复制按钮里面,都输出("clip不为控"),不是null的Clipboard经过getContents(this)为什么就变为null的呢
    ***********
    但是在copy按钮的代码里面:即使我什么都没选择,点击复制的时候,都输出("clip不为控"); 
    s=note.ta.getSelectedText();
    System.out.println(s);
    if(s!=null){
    System.out.print("不为空"+s);
    to_clip=new StringSelection(s);
    clip.setContents(to_clip,null);
    System.out.println(clip.toString());
    if(clip!=null){
    System.out.println("clip不为控");
    }else{
    System.out.println("clip为控");
    }
    }