0

I am a beginner with JavaFX and would like to create a simple Pounds to Ounces converter. I am able to get the textField from the Pounds and do calculations but when I try to setText for the Ounces field my field is not updating. Where am I going wrong?

public class LbsOzConverter2 extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent parent = FXMLLoader.load(getClass().getResource("LbsOzConverter2.fxml"));

    Scene scene = new Scene(parent);

    stage.setScene(scene);
    stage.show();
}

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

}

public class LbsOzConverter2Controller {

@FXML
private Button btnToOunces;

@FXML
private TextField tfLBS;
TextField tfOZ;

@FXML
private Label lblLBS;
private Label lblOZ;
private Label label;

public void initialize()
{
    // test text field
    tfOZ = new TextField();
    tfOZ.setText("test value");
}

// Event listener for the btnToOunces button
public void btnToOuncesListener(ActionEvent event)
{
    final double OZ_CONVER_FACTOR = 16;

    // Get the pounds from the TextField
    String str = tfLBS.getText();
    System.out.println(str);

    // Convert pounds to Ounces
    double oz = Double.parseDouble(str) * OZ_CONVER_FACTOR;
    System.out.println(str);

    // Display the converted weight 
    tfOZ.setText(""+oz);
    System.out.println(tfOZ.getText());
}   

}

DeniseG
  • 11
  • 1
  • Never initialize fields that are supposed to be injected from FXML. – James_D Dec 12 '17 at 19:20
  • If I remove the line "tfOZ = new TextField()" I receive a NFP error. What would cause the NFP error? I have looked at the other postings and I don't see how this is a duplicate, thus my reason for posting. – DeniseG Dec 12 '17 at 19:42
  • Read the linked question. You didn't annotate `tfOZ`, hence it is not injected from the FXML. At the end of my answer to that question: "So [code...] will work, but [code just like yours] will not." – James_D Dec 12 '17 at 19:44

0 Answers0