聆听粘贴事件JTextArea [英] Listen to the paste events JTextArea
问题描述
当用户粘贴JTextArea中的文本时,我想调用一个函数。当文本粘贴到JTextArea时,是否有任何事件生成,哪个侦听器可以用于触发此事件的函数?
I want to call a function when the user pastes text in my JTextArea. Is there any event generated when the text is pasted to the JTextArea and which listener can I use to trigger my function on this event?
推荐答案
p>一个可能的解决方案(我希望有一个更好的解决方案)将替换负责实际执行粘贴操作的键绑定 Action
。
One possible solution (and I hope some one has a better one) would be to replace the key binding Action
responsible for actually performing the paste operation.
现在,在执行此操作之前,默认的粘贴操作不是微不足道,而是用代理替换默认的粘贴 Action
,可以称之为原始的,但是允许您截取操作,但不必自行重新实现功能,例如...
Now, before you do this, the default paste operation is not trivial, instead, I would replace the default paste Action
with a proxy, which could call the original, but would allow you to intercept the operation, but not have to re-implement the functionality yourself, for example...
public class ProxyAction extends AbstractAction {
private Action action;
public ProxyAction(Action action) {
this.action = action;
}
@Override
public void actionPerformed(ActionEvent e) {
action.actionPerformed(e);
System.out.println("Paste Occured...");
}
}
然后你只需要看添加默认的 Action
并替换它...
Then you would simply need to look up the default Action
and replace it...
JTextArea ta = new JTextArea(10, 10);
Action action = ta.getActionMap().get("paste-from-clipboard");
ta.getActionMap().put("paste-from-clipboard", new ProxyAction(action));
这里的问题是,这不会告诉你操作失败或成功,实际上粘贴。为此,您可以在调用默认 Action
之前注册的 DocumentListener
,该记录可以记录文档的更改。显然,你想在默认动作之后取消注册;)...
The problem here is, this won't tell you if the operation failed or succeeded or what was actually pasted. For that, you could use a DocumentListener
, registered before you call the default Action
which could record the changes to the document. Obviously, you'd want to deregister this after the default action ;)...
现在,同样地,你可以覆盖 / code>方法的
JTextArea
,这相当于同样的事情,但是第一个选项将更加便携...
Now, equally, you could just override the paste
method of the JTextArea
, which equates to about the same thing, but, the first option would be more portable...
作为一个想法...
Take a look at How to Use Actions and How to Use Key Bindings for more details
这篇关于聆听粘贴事件JTextArea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!