I'm trying to make a simple calculator with a graphical user interface; however, I'm having trouble adding two values from the text fields. Each time I try and calculate the values, I receive an exception. Could someone help me out with this? I'm fairly new to java, and I'm open to feedback and suggestions. The exception is down below.
Thank you,
Kyle
public class Calculator extends Application
{
private Label firstValue;
private Label secondValue;
private Label sum;
private Button myButton;
private TextField textSum;
private TextField textFirst;
private TextField textSecond;
public String calculation()
{
String getTextFirst = textFirst.getText();
String getTextSecond = textSecond.getText();
int total = Integer.parseInt(getTextFirst) +
Integer.parseInt(getTextSecond);
String realTotal = String.valueOf(total);
return realTotal;
}
public void start(Stage myStage)
{
myStage.setTitle("Simple Calculator");
GridPane rootNode = new GridPane();
rootNode.setAlignment(Pos.CENTER);
rootNode.setPadding(new Insets(30));
Scene myScene = new Scene (rootNode, 400 , 300);
firstValue = new Label ("First Value: ");
secondValue = new Label ("Second Value: ");
sum = new Label ("Sum is: ");
textFirst = new TextField();
textSecond = new TextField();
textSum = new TextField();
textSum.setEditable(false);
myButton = new Button ("Calculate");
rootNode.add(firstValue, 1, 0);
rootNode.add(textFirst, 2, 0);
rootNode.add(secondValue, 1, 1);
rootNode.add(textSecond, 2, 1);
rootNode.add(sum, 1, 2);
rootNode.add(textSum, 2, 2);
rootNode.add(myButton, 2, 3);
myButton.setOnAction(new ButtonHandler());
myStage.setScene(myScene);
myStage.show();
}
class ButtonHandler implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
Calculator finalTotal = new Calculator();
myButton.setText("Calculating");
textSum.setText(finalTotal.calculation());
}
}
public static void main(String[] args)
{
launch(args);
}
}
Exception in thread "JavaFX Application Thread"
java.lang.NullPointerException
at Calculator.calculation(Calculator.java:22)
at Calculator$ButtonHandler.handle(Calculator.java:75)
at Calculator$ButtonHandler.handle(Calculator.java:1)