我正在尝试实现剪贴板更改事件监听器,我真的卡住了。找不到一个如何实现它的工作示例,或者找不到完整或不工作的任何工作示例。所以我试图实现这个功能的原型,但它有一个bug ...所以每当剪贴板内容改变时我想看一个弹出菜单
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.Transferable;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class MyTextArea extends JFrame implements ClipboardOwner, FlavorListener{
JTextArea textArea;
Clipboard clip;
public MyTextArea()
{
this.setSize(500, 500);
textArea = new JTextArea(40, 40);
clip = Toolkit.getDefaultToolkit().getSystemClipboard();
clip.setContents(clip.getContents(null), this);
clip.addFlavorListener(this);
Container cp = this.getContentPane();
cp.setLayout(new FlowLayout());
cp.add(textArea);
}
@Override
public void flavorsChanged(FlavorEvent e) {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog (null, "Flavour Changed","Error", JOptionPane.ERROR_MESSAGE);
clip.removeFlavorListener(this);
clip.setContents(clip.getContents(null), this);
clip.addFlavorListener(this);
}
@Override
public void lostOwnership(Clipboard arg0, Transferable arg1) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
JFrame frame = new MyTextArea();
frame.setVisible (true);
frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
}
}
是否有人如何使此代码正常工作?