3

When i create the KeyListener, it requires the following fields:

public void keyPressed(KeyEvent e) 
{

}
public void keyReleased(KeyEvent e) 
{

}
public void keyTyped(KeyEvent e) 
{

}

When i put System.out.println(e) into the keyPressed method, though, it returns this when i press the enter key:

java.awt.event.KeyEvent[KEY_PRESSED,keyCode=10,keyText=?,keyChar=?,keyLocation=KEY_LOCATION_STANDARD,rawCode=0,primaryLevelUnicode=0,scancode=0] on javax.swing.JButton[,1,1,100x100,alignmentX=0.0,alignmentY=0.5,border=com.apple.laf.AquaButtonBorder$Dynamic@13b33a0e,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=2,bottom=0,right=2],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=HI,defaultCapable=true]

This is obviously not a KeyEvent, so I cannot use it to call the keyPressed(KeyEvent e). What I want to be able to do is simulate the pressing of a key, specifically the enter key, in a way that would activate the keyListener and would output that text into a JTextArea.

Note: I looked at the accepted answer for How can I perfectly simulate KeyEvents?, and understood little of how it actually works, and i want code i understand. I also looked here How to simulate keyboard presses in java?, but not i could not get the robot to work; nothing happened when a key was supposed to be pressed.

Community
  • 1
  • 1
Harper
  • 140
  • 2
  • 4
  • 10
  • 4
    Consider not telling us how you're trying to solve this with code because I strongly suspect that you're going about this all wrong -- you usually don't create KeyEvents -- but instead tell us what problem overall you're trying to solve. In other words, tell us *what* behavior are you trying to have your GUI achieve, rather than *how* you're trying to achieve this behavior. – Hovercraft Full Of Eels Feb 14 '13 at 02:54
  • This depends on what it is you're trying to achieve. (ps- If you can't understand the answer from the [How can I perfectly simulate KeyEvents](http://stackoverflow.com/questions/14572270/how-can-i-perfectly-simulate-keyevents) question, I suspect you're not going to like any answer we give ;)) – MadProgrammer Feb 14 '13 at 02:58
  • OK, sorry. upon rereading that i do realize that i am closing off a lot of possibilities that i am not yet aware of. I'll edit it now. – Harper Feb 14 '13 at 03:00
  • @MadProgrammer The main point i didn't like was the threading and dispatch events. i have an extremely small amount of knowledge of the first, and none of the second, and neither were explained there. even an explanation of that here would be great. – Harper Feb 14 '13 at 03:06
  • @Harper The result will depend. Do you want to "dispatch" the event or simply pass it back via the `KeyListener` interface (ie `kl.keyPressed(myHandedMadeEvent)`? – MadProgrammer Feb 14 '13 at 03:08
  • You're still telling us nothing about what you're trying to do with all of this. This is the most important part of your question, and yet you're leaving us in the dark on it -- why?? – Hovercraft Full Of Eels Feb 14 '13 at 03:10
  • @MadProgrammer I want it to activate my code for the keyListener. – Harper Feb 14 '13 at 03:12
  • @HovercraftFullOfEels I believe it would make part of my code more efficient. When certain conditions are met (I am doing hang man, and this is a "cheat" that is a joke with my teacher) the computer will press the correct keys to "guess" the answer. and then there is the simple, i wonder if i can? part of it. that got started when i saw JButton.doClick() and wondered if it had one for JTextFields – Harper Feb 14 '13 at 03:15

4 Answers4

5

e is the KeyEvent.

if you want to see the e value, then you can try this

System.out.println(e.getKeyChar());

Creating KeyEvent :

KeyEvent e = new KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation);

Example (dunno if this is the right way, but it produce the right output):

Button a = new Button("click");
    KeyEvent e;
    e = new KeyEvent(a, 1, 20, 1, 10, 'a');
    System.out.println(""+e.getKeyChar());
    System.out.println(""+e.getKeyCode());

Here is the all type of KeyEvent parameters

java.​awt.​event.​KeyEvent
@Deprecated public KeyEvent(Component source, int id, long when, int modifiers, int keyCode)
Deprecated. as of JDK1.1

===

java.​awt.​event.​KeyEvent
public KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar)
Constructs a KeyEvent object.
Note that passing in an invalid id results in unspecified behavior. This method throws an IllegalArgumentException if source is null.
Parameters:
source - the Component that originated the event id - an integer identifying the type of event when - a long integer that specifies the time the event occurred modifiers - the modifier keys down during event (shift, ctrl, alt, meta) Either extended _DOWN_MASK or old _MASK modifiers should be used, but both models should not be mixed in one event. Use of the extended modifiers is preferred. keyCode - the integer code for an actual key, or VK_UNDEFINED (for a key-typed event) keyChar - the Unicode character generated by this event, or CHAR_UNDEFINED (for key-pressed and key-released events which do not map to a valid Unicode character) 
Throws:
IllegalArgumentException - if id is KEY_TYPED and keyChar is CHAR_UNDEFINED; or if id is KEY_TYPED and keyCode is not VK_UNDEFINED IllegalArgumentException - if source is null

===

java.​awt.​event.​KeyEvent
public KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar, int keyLocation)
goravine
  • 266
  • 3
  • 11
  • *"my question, basically, is how do you create a a KeyEvent?*" – MadProgrammer Feb 14 '13 at 02:59
  • That returns a char, not a KeyEvent. I want to say keyPressed(myOwnKeyCode)to simulate what e would be for a normal keystroke. – Harper Feb 14 '13 at 02:59
  • That worked well. Could you, or anyone, explain int modifiers, long when, and why int keyLocation appears to be a char for a? sorry, I often try to understand more than is good for my level of knowledge. – Harper Feb 14 '13 at 03:27
  • @harper for the int modifier and long when is still a mystery for me. maybe you can search the java help. for the int keyLocation there are several parameter that you doesn't have to fill. check my updated answer – goravine Feb 14 '13 at 03:43
  • Thank you, both for the code and the full explanation. i understand and it works incredibly simply compared to what i have seen around the internet. – Harper Feb 14 '13 at 03:50
2

When using robot, first obtain focus of component to which you add your KeyListener to. Then you can use robot to simulte key presses. As an alternative, you can just use dispatchEvent on component to which your listener is added.

KeyEvent key = new KeyEvent(inputField, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'Z');
inputField.dispatchEvent(key);

Providing you have:

JInputField InputField = new JInputField();

You can as well create KeyEvent as described above and pass it to keyTyped method of your listener. As for keyPrssed, you can do the same.

Conarh
  • 31
  • 3
1

You state:

I believe it would make part of my code more efficient. When certain conditions are met (I am doing hang man, and this is a "cheat" that is a joke with my teacher) the computer will press the correct keys to "guess" the answer. and then there is the simple, i wonder if i can? part of it. that got started when i saw JButton.doClick() and wondered if it had one for JTextFields

As I suspected, you are going about this all wrong. If you want your program to press keys for you, there's no need to create KeyEvents. If the "keys" are JButtons, then simply calling doClick() on the button will do. If you are desiring to fill text into a JTextField, then simply setting the text is all that is needed. i.e.,

For instance if you called the bit of text below in a Swing Timer (to slow it down so that you see the text being added:

String myText = myTextField.getText();
myText += nextBitOfText;
myTextField.setText(myText);

You would likely get the effect you desire.

For example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;

@SuppressWarnings("serial")
public class AddTextToTextField extends JPanel {
   public static final String[] POSSIBLE_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
   public static final int TIMER_DELAY = 500;
   private JTextField myTextField = new JTextField(20);
   private JButton myButton = new JButton(new BtnAction("Press Me"));
   private Random random = new Random();

   public AddTextToTextField() {
      add(myTextField);
      add(myButton);
   }

   private class BtnAction extends AbstractAction {
      public BtnAction(String text) {
         super(text);
      }

      @Override
      public void actionPerformed(ActionEvent arg0) {
         setEnabled(false);
         myTextField.setText("");
         myTextField.setFocusable(false);
         String randomText = POSSIBLE_TEXTS[random.nextInt(POSSIBLE_TEXTS.length)];
         new Timer(TIMER_DELAY, new TimerAction(this, randomText)).start();
      }
   }

   private class TimerAction implements ActionListener {
      private AbstractAction btnAction;
      private String text;
      private int count = 0;

      public TimerAction(AbstractAction btnAction, String text) {
         this.btnAction = btnAction;
         this.text = text;
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         if (count <= text.length()) {
            myTextField.setText(text.substring(0, count));
            count++;
         } else {
            ((Timer)e.getSource()).stop();
            btnAction.setEnabled(true);
            myTextField.setFocusable(true);
         }
      }
   }

   private static void createAndShowGui() {
      AddTextToTextField mainPanel = new AddTextToTextField();

      JFrame frame = new JFrame("AddTextToTextField");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Yes, but i also want it to set off the keyListener to activate a corresponding event. An action in the JTextArea is of second rate importance. Sorry if that appeared to be my main concern in that comment. – Harper Feb 14 '13 at 03:30
  • @Harper: what "corresponding event"? – Hovercraft Full Of Eels Feb 14 '13 at 03:32
  • @HovercraftFullOfEels i have a keyListener set up and i have several things that are supposed to happen with keyPressed(KeyEvent e). My main concern is setting off that, as creating methods that react to an input and affect certain JTextFields is much more difficult than using e.getSource() from within the KeyListener. – Harper Feb 14 '13 at 03:36
  • @Harper: you're still being vague about the specifics. Also note that for Swing applications you should avoid using low-level KeyListeners to begin with. One reason is that they require focus for function, and there are much better ways of handling key listening such as use of bindings. If clarify your requirements some more, I'm guessing that we'll be able to better help you. – Hovercraft Full Of Eels Feb 14 '13 at 03:39
  • OK, here's my attempt to be as specific as possible: I am coding a 2 player game of hangman. the first player inputs a word, which is put into a string (String input = inArea.getText();) then i process this into a char array (input.toCharArray(). our teacher requires the use of an array) i then set up the hangman board with the required number of blank JLabels for the word, then a JTextField for guessing. when a letter is input and enter is hit, it processes that letter tto see if the array contains it. i want a "cheat" button to take the chars, input them, and hit enter to auto-win the game – Harper Feb 14 '13 at 03:47
  • @HovercraftFullOfEels Why play police? its either you just don't want to understand his requirements else i don't know. His requirement is clear and very reasonable. imagine a scenario where you have a virtual key board that should act as an alternative in the absence of a keyboard, How would you fire relevant key-pressed, key-typed and key-released event? Normally with a keyboard every time a key is pressed, released or typed, Relevant events get fired, How would one have those events fired within a virtual keyboard scenario? – katwekibs Dec 16 '16 at 17:37
0

You can use this to dispatch a virtual event:

textArea.dispatchEvent(new KeyEvent(jFrame,
        KeyEvent.KEY_TYPED, System.currentTimeMillis(),
        0,
        KeyEvent.VK_ENTER));

Try that out, it should work but that was from memory

Tips48
  • 745
  • 2
  • 11
  • 26
  • *"You don't 'create' it"* - Well, technically, you can. It's not advised and if you have a read of the links he posted, it will show you how it can be done... – MadProgrammer Feb 14 '13 at 03:00
  • Yea, you have a point. I just figured in his context it wasn't even worth mentioning. Updating answer – Tips48 Feb 14 '13 at 03:01
  • It's a nit pick to be sure ;) – MadProgrammer Feb 14 '13 at 03:02
  • Obviously :P Updated my answer to include a possible method of faking a key stroke and clarifying that it's possible to create an event, but there are safer methods. – Tips48 Feb 14 '13 at 03:04
  • What do you mean by "use the one passed to you"? I am trying to simulate this without an actual key being pressed. – Harper Feb 14 '13 at 03:07
  • What are those safer methods? I will accept anything as long as you can explain why it works. – Harper Feb 14 '13 at 03:08
  • Yea, I just now noticed that. Checkout that robot class, and if it doesn't work the poster below me probably has the most likely solution. Create the object and then you can pass it manually. – Tips48 Feb 14 '13 at 03:08
  • By "safer methods" I meant something like robot, although I see now you said it doesn't work for you. Updating my answer now – Tips48 Feb 14 '13 at 03:10
  • Edited my answer (again!), this time with what you want. When I first read the question I think you either edited it with more information or it was incomplete or something. – Tips48 Feb 14 '13 at 03:13
  • yes, i did edit it, after i realized that i had asked in an odd, semi-incorrect way. – Harper Feb 14 '13 at 03:16
  • Eclipse is giving me the message that "the constructor KeyEvent(Component, int, long, int, int) is deprecated". Any other suggestions? – Harper Feb 14 '13 at 03:19