views:

56

answers:

1

Hi, 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  A: 

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'));
Grodriguez
Yes, it is a virtual keyboard and no I don't have the focus on the text field. I'll try this out as soon as I get back to the project.
viraptor
Make sure to check the other suggestion as well (pass the target component as `source` of the `KeyEvent`). I had this same problem in a project of mine.
Grodriguez
And yeah - works now :)
viraptor
Very good. Glad to help :-)
Grodriguez
Also, for future reference, I didn't need the focus. Setting the text field as the event source and adding proper time was enough.
viraptor
Good. I believe the component *must* be focusable, though, even if it does not currently have the focus. This is not an issue for standard components, though.
Grodriguez