发送按键到JTextField [英] Sending keypresses to JTextField
问题描述
我正在尝试将文本输入模拟成一个 JTextField
。我有一个1字符长的字符串,包含我要添加的字母,我运行:
I'm trying to simulate text input into a JTextField
. I've got a 1 char long string containing the letter I want to add and I run:
receiver.dispatchEvent(new KeyEvent(this,
KeyEvent.KEY_TYPED, 0,
this.shifted?KeyEvent.SHIFT_DOWN_MASK:0,
KeyEvent.VK_UNDEFINED, text.charAt(0)));
但这似乎根本不改变内容。我在这里缺少什么?
But this doesn't seem to change the contents at all. What am I missing here?
推荐答案
看起来像一个虚拟键盘给我: - )
Looks like a virtual keyboard to me :-)
几乎完全相同的代码对我有用。我会建议以下内容:
Almost the exact same code does work for me. I would suggest the following:
-
传递目标
JTextField
(in您的案例接收者
)作为源参数
KeyEvent
构造函数,即:
Pass the target
JTextField
(in your case,receiver
) as thesource
parameter to theKeyEvent
constructor, i.e.:
receiver.dispatchEvent(new KeyEvent(receiver,
KeyEvent.KEY_TYPED, System.currentTimeMillis(),
modifiers, KeyEvent.VK_UNDEFINED, keyChar);
确保您的目标
Ensure your target JTextField
has the focus.
编辑: JTextField
只是为了验证上述建议,我测试了这段代码:
Just to verify the above suggestion, I tested this snippet of code:
Frame frame = new Frame();
TextField text = new TextField();
frame.add(text);
frame.pack();
frame.setVisible(true);
text.dispatchEvent(new KeyEvent(frame,
KeyEvent.KEY_TYPED, 0,
0,
KeyEvent.VK_UNDEFINED, 'H'));
这样做es不工作,但是如果最后一行被修改如下(目标组件作为 source
参数的 KeyEvent
构造函数),它工作正常:
This does not work, however if the last line is modified as follows (target component as the source
parameter of the KeyEvent
constructor), it works fine:
text.dispatchEvent(new KeyEvent(text,
KeyEvent.KEY_TYPED, 0,
0,
KeyEvent.VK_UNDEFINED, 'H'));
这篇关于发送按键到JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!