Java Reference
In-Depth Information
23 gridPane.setHgap( 5 );
24 gridPane.setVgap( 5 );
25 gridPane.add( new Label( "Annual Interest Rate:" ), 0 , 0 );
26 gridPane.add(tfAnnualInterestRate, 1 , 0 );
27 gridPane.add( new Label( "Number of Years:" ), 0 , 1 );
28 gridPane.add(tfNumberOfYears, 1 , 1 );
29 gridPane.add( new Label( "Loan Amount:" ), 0 , 2 );
30 gridPane.add(tfLoanAmount, 1 , 2 );
31 gridPane.add( new Label( "Monthly Payment:" ), 0 , 3 );
32 gridPane.add(tfMonthlyPayment, 1 , 3 );
33 gridPane.add( new Label( "Total Payment:" ), 0 , 4 );
34 gridPane.add(tfTotalPayment, 1 , 4 );
35 gridPane.add(btCalculate, 1 , 5 );
36
37 // Set properties for UI
38 gridPane.setAlignment(Pos.CENTER);
39 tfAnnualInterestRate.setAlignment(Pos.BOTTOM_RIGHT);
40 tfNumberOfYears.setAlignment(Pos.BOTTOM_RIGHT);
41 tfLoanAmount.setAlignment(Pos.BOTTOM_RIGHT);
42 tfMonthlyPayment.setAlignment(Pos.BOTTOM_RIGHT);
43 tfTotalPayment.setAlignment(Pos.BOTTOM_RIGHT);
44 tfMonthlyPayment.setEditable( false );
45 tfTotalPayment.setEditable( false );
46 GridPane.setHalignment(btCalculate, HPos.RIGHT);
47
48
add to grid pane
// Process events
49
btCalculate.setOnAction(e -> calculateLoanPayment());
register handler
50
51 // Create a scene and place it in the stage
52 Scene scene = new Scene(gridPane, 400 , 250 );
53 primaryStage.setTitle( "LoanCalculator" ); // Set title
54 primaryStage.setScene(scene); // Place the scene in the stage
55 primaryStage.show(); // Display the stage
56 }
57
58 private void calculateLoanPayment() {
59 // Get values from text fields
60 double interest =
61 Double.parseDouble(tfAnnualInterestRate.getText());
62 int year = Integer.parseInt(tfNumberOfYears.getText());
63 double loanAmount =
64 Double.parseDouble(tfLoanAmount.getText());
65
66 // Create a loan object. Loan defined in ListingĀ 10.2
67 Loan loan = new Loan(interest, year, loanAmount);
68
69 // Display monthly payment and total payment
70 tfMonthlyPayment.setText(String.format( "$%.2f" ,
71 loan.getMonthlyPayment()));
72 tfTotalPayment.setText(String.format( "$%.2f" ,
73 loan.getTotalPayment()));
74 }
75 }
get input
create loan
set result
The user interface is created in the start method (lines 22-46). The button is the source of
the event. A handler is created and registered with the button (line 49). The button handler
invokes the calculateLoanPayment() method to get the interest rate (line 60), number of
years (line 62), and loan amount (line 64). Invoking tfAnnualInterestRate.getText()
returns the string text in the tfAnnualInterestRate text field. The Loan class is used for
 
Search WWH ::




Custom Search