Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

keyboard events  RSS feed

 
mike smith
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to output key the user presses. why won't this work? I don't think it is catching the key event.
 
Dorothy Finkel-Laverty
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, first of all, it won't compile. In your keyPressed method, you are calling getKeyText(), which requires an int as an argument. I suspect you meant to use getKeyChar().
Second, you need to add the KeyListener object to the component that is visible - that is, to the JTextField showkey, not to the container pane.
Try it. You should see both your keyPressed and keyTyped event handlers for the character keys, and just your keyPressed for the non-typeable keys.
One more suggestion - while you're learning, you may want to include in your printout the name of method that is showing the information, such as "System.out.print("in keyPressed " + x);" or "System.out.print("in keyTyped " + key);". Helps you to learn the differences between a keyPressed, keyTyped, and keyReleased.
Have fun!
 
mike smith
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks, i'll try that. And yea I have been using the system output commands for learning and debugging purposes.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!