目录
题目:*16.13(比较不同利率的贷款)
改写编程练习题5.21,创建一个图形用户界面,如图16-41b所示。程序应该允许用户从文本域输入贷款额以及以年为单位的贷款年限,在文本域中会显示关于每种利率的月偿还额和总偿还额,利率从5%到8%,按1/8(0.125%)递增。
-
习题思路
- 新建一个TextArea(全局变量),创建一个ScrollPane,传入TextArea
- 创建一个HBox,新建两个Label和两个TextField,以及一个按钮Button,
- 创建一个BorderPane,将ScrollPane设置在中心,把HBox设置在顶部
- 为Button注册一个事件,当按钮按下时检查两个TextField是否为空,不为空则用输入框里的内容为参数传入一个输出到TextArea的方法
- (输出到TextArea的方法)每次调用前清除之前的文本,用TextArea.appendText()方法代替System.out.println()
-
代码示例
编程练习题16_13CompareLoans.java
package chapter_16;
import java.lang.invoke.StringConcatFactory;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class 编程练习题16_13CompareLoans extends Application{
private TextArea textArea = new TextArea();
@Override
public void start(Stage primaryStage) throws Exception {
ScrollPane scrollPane = new ScrollPane(textArea);
HBox hBox = new HBox(10);
TextField tfLoan = new TextField();
Label lbLoan = new Label("Loan Amount",tfLoan);
lbLoan.setContentDisplay(ContentDisplay.RIGHT);
TextField tfYear = new TextField();
tfYear.setPrefWidth(30);
Label lbYear = new Label("Number of Years",tfYear);
lbYear.setContentDisplay(ContentDisplay.RIGHT);
Button btShow = new Button("Show Table");
hBox.getChildren().addAll(tfLoan,lbLoan, tfYear,lbYear, btShow);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(scrollPane);
borderPane.setTop(hBox);
btShow.setOnMouseClicked(e ->{
if(!tfLoan.getText().isEmpty()&&!tfYear.getText().isEmpty()) {
double loan = Double.valueOf(tfLoan.getText());
int year = Integer.valueOf(tfYear.getText());
print(loan, year);
}
});
Scene scene = new Scene(borderPane,500, 200);
primaryStage.setTitle("编程练习题16_13CompareLoans");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
public void print(double Loan, int Years) {
textArea.clear();
double rate = 5.000;
textArea.appendText("Interest Rate\t\tMonthly Payment\tTotal Payment\n");
while(rate<=8.000) {
textArea.appendText(rate+"% ");
double monthly_Rate = (rate/1200);
double monthly_Pay = (Loan * monthly_Rate )/ (1 - 1/Math.pow(1+monthly_Rate,Years*12));
double total_Pay = monthly_Pay * 5 * 12;
textArea.appendText("\t\t"+Math.round(monthly_Pay*100.0)/100.0);
textArea.appendText("\t\t\t"+Math.round(total_Pay*100.0)/100.0+"\n");
rate+=0.125;
}
}
}
-
结果展示