viraptor
viraptor

Reputation: 34205

Sending keypresses to JTextField

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?

Upvotes: 2

Views: 6546

Answers (1)

Grodriguez
Grodriguez

Reputation: 22025

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

Upvotes: 2

Related Questions