Hi, I have just created buttons with labels as numbers(0-9) and some operators like(+,-,/,=) using grid layout and then created a text box. Now here i got a problem and i want to know how to link these buttons with text box.That is how to write the code if i press a button the label should be displayed on the textbox.
sounds like a calculator, so look at what happens when you use a calculator, and you press the keys 1 2 3 the display changes to 1 then 12 then 123
to do this with a textField (should be uneditable, or use a JLabel), you use textField.setText(), textField.getText() and button.getText() (or other ways for what number the button represents)
so, when the calculator first starts, textField.getText() will be "", press the 1 key and actionPerformed will be textField.setText(textField.getText()+button.getText()); which is ""+"1", and will display 1 press the 2 key = "1"+"2" = 12 press the 3 key = "12"+"3" = 123
different story for the operators, but this should be enough to get you started
Thanks for our reply. Then how about operators? if we press 1 2 then the display is 12 but if we press the key + then also the display is 12
Now if we press 2 then the display should be 2
And again if we press the key + then the display is 14
Now here i got a problem with the operators how to write the code. Can any one suggest me.
Joined: Jun 09, 2003
you need to store: 1) the operator pressed prior to the new numbers 2) a boolean to check whether the last key pressed was an operator, if so, when a number is pressed the display is 'set', not 'appended' i.e. textfield.setText(button.getText()); instead of textfield.setText(textfield.getText()+button.getText()); 3) the current display value
if the operator is '=', you would clear the above variables after displaying the total
so, it would be something along these lines int operatorKeyCode = KeyEvent.VK_EQUALS; double displayTotal = 0.00; boolean lastKeyOperator = true;
if you now press the keys 1 + 2 =
1: checks lastKeyOperator (true) changes the display to 1 changes lastKeyOperator to false