OK the code below is nasty I know. It's a hack of an example from Head First Java. I'm trying to diaply 3 text fields and a button. This I have managed, yes it looks nasty buy the cosmetics I can work on later. Only problem is I cant figure out how to get the button to work.
What do I need to add below to get the button to point to another piece of code to add the values in the 3 boxes? eg you enter a value into each of the three boxes in the North, West & East and when you press the button it returns the sum in the center?
Thanks for the link. I have read through it and bits make sense but It's all still very confusing to me. I've seen a few examples of buttons doing things but even the simplest ones such as 'Beeper' appear hideously complicated.
What exactly is 'this' in the code below? button1.addActionListener(this);
this is a reference to the class that 'this' is in. Appearntly you are referring to when a class implements ActionListener then that syntax is adding a reference to that class to the button as the actionListener. Here is a simpler way, and by most, the preferred way for simple actions.
1. You've declared sym as a JTextField variable in your go() method. Because of the rules of scope, sym is only accessible in the go() method unless you pass a reference of it to some other method. You need to make sym a global / instance variable of the class, like you did your JButton.
2. Once you have 1 solved you are going to get another exception because you can't convert a JTextField to a float. You need to use the getText() method of the JTextField.
Great. I now think it works. However I can't seem to diaplay the result in the CENTER of the frame, or indeed anywhere.
I thought I would be able to add
in the section of code that is called when the Calculate button is hit. And this would return the result in the center of the frame. However it does not. Do I need to pass the 'sum' back to 'go' as a global value?
Anytime you add or remove widgets to/from a container, after the container has been realized, you need to call the validate() method on the container so it can rebuild itself from the layout and repaint all the widgets.
This seems a strange way to display results for a calculator type application. Seems it would be better to have another textfield or a label that you simply update with the new value.