Sending keypresses to JTextField

前端 未结 1 882
闹比i
闹比i 2021-01-07 07:48

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.dis         


        
相关标签:
1条回答
  • 2021-01-07 08:43

    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'));
    
    0 讨论(0)
提交回复
热议问题