使用解析Double时,应用程序启动方法java.lang.reflect.InvocationTargetException中的异常

时间:2018-07-27 16:15:05

标签: parsing javafx

因此,我正在尝试使GUI可以用于编程项目。这涉及将其从简单的扫描功能更改为使用parse Double从文本字段转换用户输入。该程序可以运行,但是一旦我进行了更改,它就会在标题中引发异常,并在每次运行它时终止该程序。是的,我有一个主要方法。

以下是相关代码:

public class TaxProject extends Application implements 
EventHandler<ActionEvent>
{
private Stage primaryStage;
private Button button;

public void start(Stage primaryStage) 
{
    Scanner input = new Scanner(System.in);
    TaxInput t1 = new TaxInput();
    StateTax s1 = new StateTax();   //Declaring Classes
    FedTax f1 = new FedTax();
    GridPane pane = new GridPane();
    pane.setPadding(new Insets(10, 10, 10, 10));
    pane.setVgap(8);
    pane.setHgap(10);


    TextField tfHrlyWage = new TextField();
    TextField tfHrsPerWeek = new TextField();
    TextField tfMaritalStatus = new TextField();
    TextField tfIncome = new TextField();
    Button btCalculate = new Button("Calculate");
    pane.add(new Label("Hourly Wage: "), 0, 0);
    pane.add(new Label("Hours Per Week: "), 0, 1);
    pane.add(new Label("Married or Single? "), 0, 2);
    pane.add(btCalculate, 0, 3);
    pane.add(tfHrlyWage, 1, 0);
    pane.add(tfHrsPerWeek, 1, 1);
    pane.add(tfMaritalStatus, 1, 2);
    pane.add(tfIncome, 1, 0);




    tfHrlyWage.setPrefColumnCount(4);
    tfHrsPerWeek.setPrefColumnCount(3);
    tfMaritalStatus.setPrefColumnCount(7);
    tfIncome.setPrefColumnCount(7);


    Scene scene = new Scene(pane, 250,150);
    primaryStage.setTitle("Tax Calculator");
    primaryStage.setScene(scene);
    primaryStage.show();

    String MaritalStatus;  //Used for deciding federal income tax brackets
    //System.out.println("Please Enter your Hourly Wage:");
    t1.HrlyWage = Double.parseDouble(tfHrlyWage.getText()); //HourlyWage Input
    //System.out.println("Please Enter the hours you work per week:");
    t1.HrsPerWeek = Double.parseDouble(tfHrsPerWeek.getText());
    MaritalStatus = tfMaritalStatus.getText();
    btCalculate.setOnAction(e -> System.out.println("Your Yearly Income After Federal and State Income Taxes is $" + f1.YearlyTakeHome));

1 个答案:

答案 0 :(得分:1)

start方法只是设置GUI。没有什么会使代码像使用扫描仪的控制台程序那样等待用户输入。

JavaFX是基于事件的,您应该找到一些事件/属性以向其中添加事件处理程序/侦听器并对事件/更改做出反应。

如果您希望在更改文本字段内容时自动更新结果,则这可能是text的{​​{1}}属性的侦听器

TextField

或从侦听器到按钮事件处理程序:

//t1.HrlyWage = Double.parseDouble(tfHrlyWage.getText());
//t1.HrsPerWeek = Double.parseDouble(tfHrsPerWeek.getText());

InvalidationListener listener = o -> {

    try {
        t1.HrlyWage = Double.parseDouble(tfHrlyWage.getText());
        t1.HrsPerWeek = Double.parseDouble(tfHrsPerWeek.getText());

        // TODO: some output???
    } catch (NumberFormatException ex) {
        // TODO: output error message???
    }

};

tfHrlyWage.textProperty().addListener(listener);
tfHrsPerWeek.textProperty().addListener(listener);