I think you are going about the whole exercise the wrong way, I am afraid. You appear to be starting from a GUI and trying to get that to calculate, which I think is the wrong way to go about it.
How would you create a calculator without a GUI? Get that working, so you can call add(123, 456) or divide(123.45, 678.9) and get it to return an answer. Only then should you think of putting a GUI atop it.
Why on earth are you using Frame, or the show() method? It would appear you are learning programming practices which are 15 years out of date. Look up Component#show() and see what it says about it.
Campbell Ritchie wrote:It would appear you are learning programming practices which are 15 years out of date.
I think that would include the idea of using a KeyListener, too. If you're making a GUI calculator with buttons for the digits 0-9 and the operators +, * and so on, then all you should need is to use ActionListeners to respond to clicks on those buttons. There shouldn't be any need to listen for key clicks. (Especially if this is a problem for beginners.)
Joined: Nov 02, 2012
to sir campbell ritchie.
im sure ure right about everything but i have to make the calculator only using the topics we have discused in the class and Frame is the only topic taught to us for making a GUI program.
to sir paul clapham.
but my teacher is also asking that the calculations should also be done when the operator is pressed on the keyboard, therefore i looked into keyListener but cant get it to work.
Well, usually when I want to use a feature of Java, and I don't know anything about that feature, I look for a tutorial about it on the Internet. The web search keywords I use are "java X tutorial" where X is the feature in question.
You have added the key listener to the TextField which is fine but it means the keyListener will only get called if the TextField has focus when a key on the keyboard is pressed.
It's a long time since I used AWT components and I'm not sure if/how you can add a keyboard listener at the container level. One simple (albeit inelegant) option you have is to set the focus back to the TextField after every button is pressed and that way you will always get the keyboard events.
Joined: Nov 02, 2012
thank you tony i have got it to work using requestFocusInWindow() method after every actionEvent then used the getKeyChar() method to read the + - * / key stroke, so thank you for the focus tip.
thank you all of you for your help.
Joined: Oct 13, 2005
Tony Docherty wrote: . . .
It's a long time since I used AWT components . . .