yvensup
yvensup

Reputation: 75

Java calculator add numbers to textfield

I am making a calculator to test my skills in java. How can make the numbers to show up in the jTextfield until i pressed one button to calculate the numbers; i want every numbers to show up in the textfield. for example if i pressed 1 and zero i want the textfield to have 10.

int num;
JTextField in = new JTextField(20); // input field where numbers will up;

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == bouttons.get(0)) {
        num = 0;
        in.setText("" + num);
    }
    if (e.getSource() == bouttons.get(1)) {
        int num = 1;
        in.setText("" + num);
    }
}

The screenshot

Upvotes: 5

Views: 23363

Answers (4)

Deepanshu
Deepanshu

Reputation: 147

You could add ActionListener to the numeric button. For eg: if you have a JButton b1 that add 1 to the textfield... You could use it like this:

    public void actionPerformed(ActionEvent e) {
        /* I'm using equals method because I feel that it is more reliable than '==' operator
         * but you can also use '=='
         */
        if(e.getSource().equals(b1){
            in.setText(in.getText + "1");
        }
    }

And similarly you could add other buttons for 1,2,3... and implement it like this.

Hope this will help you.... :-) :-)

Upvotes: 0

An SO User
An SO User

Reputation: 24998

To save yourself the hassle of a lot of if-else you can create an array of JButtons and go over them in a loop.
So button 0 will be at index 0.

Then, you can append the text to the JTextField as:

String alreadyDisplayed = in.getText(); //get the existing text
String toDisplay = alreadyDisplayed + Integer.toString(loopCounter);// append the position to the text
in.setText(toDisplay);// display the text  

You can loop as follows:

for(int i=0;i<jbuttonArray.length;i++){
    if(e.getSource()==jbuttonArray[i]){
        //insert above code here;
    }
}

Here is the tutorial by Oracle on this subject: http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

Upvotes: 2

Mateusz
Mateusz

Reputation: 3048

You want to append the text to whatever already is there - try something like

in.setText(in.getText() + num) instead of in.setText("" + num)

Upvotes: 2

rahul maindargi
rahul maindargi

Reputation: 5625

you should append with in.getText() instead of empty String

int num ;
JTextField in = new JTextField(20); // input field where numbers will up;
public void actionPerformed(ActionEvent e) {



    if (e.getSource() == bouttons.get(0)) {

        num =0;

        in.setText(in.getText() + num);

    }

    if (e.getSource() == bouttons.get(1)) {

        int num = 1;
        in.setText(in.getText() + num);

    }

}

Upvotes: 1

Related Questions