Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A Problem related to KEYEVENTS

 
lakmal padmakumara
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm coding a java calculator at the moment. There are Buttons to add ,subtract ,Multiply....Now what I want to do is when I press + key in the keyboard it should activate the "ADD" button in the J Frame. Similarly when I press '-' key on the keyboard it should activate the 'SUB' button on J Frame.

There is a Text Field in the J Frame. When I press a key like '+' '-' '*' ...... in Key Board it should not print that sign in TextField ,instead of that it should activate the related Button on the J Frame as I have mentioned about .



I tried something like this !! But When I press + key it prints '+' on the text field .I want to avoid that because it hurts my later calculations.It should only activate actionPerformed method of that particular Button. As you know in normal Calculators when you press a operator It won't show that operator in the display.So I think you got my problem !!
 
Rob Camick
Ranch Hand
Posts: 2608
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read the section from the Swing tutorial on "How to Use Key Bindings".

Your custom Action can just invoke the doClick() method of the appropriate button.
 
lakmal padmakumara
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob the doClick() method is very helpful.But Still I could not find an answer for my question. That is
When my code is



it calls the ADD button.But it also prints the '+' sign on my Text Field .How Can I restrict that!? Because when i press equal button it gets the number on the text field and does the calculation .But if you have + sign with the number I cannot do the calculations.

Simply what i want to do is click the ADD button when I press + Key(I can obtain that functionality using doClick() method). And also to avoid the printing of + sign in the Text Field . (how to do this?)
 
Rob Camick
Ranch Hand
Posts: 2608
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(how to do this?)


I already told you that you need to use Key Bindings.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic