I am trying to get a backspace button to work. I get StringIndexOutOfBoundsException when I press it and do not know why. Any help?
The error occurs at line 121.
Look at what happens in your actionPerformed method.
Line 108: Here you make the StringBuilder empty.
Line 121: The StringBuilder is still empty, so strBuild.length() is 0, so you try to delete the character at index -1.
You want to set strBuilder to the desired content here, which is the content of the text field without the last character.
Justin Dutch wrote:I am trying to get a backspace button to work.
I'm no GUI expert, so I'm not going to try to advise on specifics like that; but it seems to me that you're mixing up the business of what a calculator does with how you display it. GUI code is all about display, and it tends to be big and cumbersome and full of boilerplate. What a calculator does is much more specific, and can be done without any GUI code at all.
Assuming that you don't want to use RPN (which is actually much simpler), the "mill" of your calculator could be an operator precedence parser (also sometimes called an "infix expression parser"), which is activated whenever you press the '=' button; otherwise, your GUI simply adds characters to a "result" field.
If your "result" field is something like a JTextField, I'm pretty sure that backspace would then work automatically, and you can take all the "calculation guts" out of your GUI and put it in a separate class that simply takes a String expression (or indeed, individual characters) and returns you a result. Personally, I'd be tempted to test this class without a GUI at all and simply supply it with characters via a Scanner (java.util.Scanner).
That way, you separate what your Calculator does from what it looks like.
Winston
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Grow a forest with seedballs and this tiny ad:
a bit of art, as a gift, the permaculture playing cards