Sending keypresses to JTextField

旧巷老猫 提交于 2019-12-03 22:48:07

问题


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?


回答1:


Looks like a virtual keyboard to me :-)

Almost the exact same code does work for me. I would suggest the following:

  1. Pass the target JTextField (in your case, receiver) as the source parameter to the KeyEvent constructor, i.e.:

    receiver.dispatchEvent(new KeyEvent(receiver,
        KeyEvent.KEY_TYPED, System.currentTimeMillis(),
        modifiers, KeyEvent.VK_UNDEFINED, keyChar);
    
  2. Ensure your target JTextField has the focus.

Edit:

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'));

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'));


来源:https://stackoverflow.com/questions/3800840/sending-keypresses-to-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!