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 !!
[Bsc in Computer Science and Engineering] [SCJP 80%][BCS certificate level]
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.
Joined: Aug 08, 2009
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?)
Joined: Jun 13, 2009
(how to do this?)
I already told you that you need to use Key Bindings.