As my first applet, I'm making a calculator (only adding at the moment), but I am stuck at figuring out how to get numbers from the listeners. So far I have:
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class calculator extends JApplet {
private JTextField num1;
private JTextField num2;
private JButton calculate;
private JLabel result;
private double numOne,numTwo;
private double sum = numOne + numTwo;
public void init() {
num1 = new JTextField("",9);
num2 = new JTextField("",9);
calculate = new JButton("Calculate");
result = new JLabel("The Answer is: " + sum);
num1.addActionListener(new num1Listener());
num2.addActionListener(new num2Listener());
calculate.addActionListener(new doMath());
add(num1);
add(num2);
add(calculate);
setLayout(new FlowLayout());
setSize(200,200);
}
public void paint(Graphics g) {
super.paint(g);
g.drawString("The answer is " + sum, 20, 20);
}
class num1Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String num1input = num1.getText();
numOne = Double.parseDouble(num1input);
}
}
class num2Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String num2input = num2.getText();
numTwo = Double.parseDouble(num2input);
}
}
class doMath implements ActionListener {
public void actionPerformed(ActionEvent e) {
add(result);
}
}
}
How can I get my numOne and numTwo doubles from inside these listeners and into my code? I would like to add them together and store them in the sum variable.