0

I am creating a simple calculator that adds two values entered in text fields and then displays the sum in a third text field when you press a button. However, when I press the button nothing happens and I cant figure out what is wrong. I don't get any error messages and the program compiles the button just doesn't seem to do anything.

import javafx.application.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.event.*;


public class Calculator extends Application{

private TextField sumField;
private TextField firstVField;
private TextField secondVField;

public void start(Stage myStage){
    myStage.setTitle("Simple Calculator");

    GridPane rootNode = new GridPane();
    rootNode.setPadding(new Insets(30));
    rootNode.setHgap(5);
    rootNode.setVgap(5);

    Scene myScene = new Scene(rootNode, 350,250);

    Label firstVLabel = new Label("First Value:");
    Label secondVLabel = new Label("Second Value:");
    Label sumLabel = new Label("Sum:");


    TextField firstVField = new TextField();
    TextField secondVField = new TextField();
    TextField sumField = new TextField();


    sumField.setEditable(false);

    Button calculate = new Button("Calculate");

    rootNode.add(firstVLabel, 0, 0);
    rootNode.add(firstVField, 1, 0);
    rootNode.add(secondVLabel, 0, 1);
    rootNode.add(secondVField, 1, 1);
    rootNode.add(sumLabel, 0, 2);
    rootNode.add(sumField, 1, 2);
    rootNode.add(calculate, 1, 3);

    myStage.setScene(myScene);
    myStage.setResizable(false);
    myStage.show();

}

class ButtonHandler implements EventHandler<ActionEvent>{

    public void handle(ActionEvent e) {
        int sum = (int)firstVField.getText() + (int)secondVField.getText();
        sumField.setText(Integer.toString(sum));

    }
}

public static void main( String [] args){
    launch(args);
}

}
grademacher
  • 67
  • 1
  • 3
  • 9

1 Answers1

1

You forgot to connect your ButtonHandlerto the calculate button

calculate.setOnAction(new ButtonHandler());
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Thats a very different issue. See [this post](http://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar) – Reimeus Mar 27 '16 at 22:21
  • changed the cast arguments to a parseInt argument and im now getting a null pointer exception. Any thoughts? – grademacher Mar 27 '16 at 22:24
  • yep. you're shadowing `sumField`. replace `TextField sumField = new TextField();` with `sumField = new TextField();` :) – Reimeus Mar 27 '16 at 22:28
  • Awesome! I had to do the same thing with the two other text fields but it worked. Thank you! – grademacher Mar 27 '16 at 22:30