Amelia J.
Amelia J.

Reputation: 126

Java calculator how to make backspace

I started learning programming a few days ago. I tried to make a calculator but i have one problem: i don't know how to make backspace JButton.

buusun.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                tf.setText(text.getText().length()-1); 
            }

        });

Any ideas?

Upvotes: 2

Views: 8645

Answers (1)

Pokechu22
Pokechu22

Reputation: 5046

Try this:

    buusun.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent arg0)
        {
            tf.setText(text.getText().substring(0, text.getText().length() - 1)); 
        }

    });

It uses the string.substring(start, end) method.
Note that you might need to adjust the exact variables you are using, as I'm not sure whether you need to get the value from tf or text, but this should provide the gist of what you want.

Upvotes: 3

Related Questions