第4周作业-贷款计算器程序

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;

public class LoanCalculator extends JFrame {
	//Create text fields for interest rate,
	//year,loan amount,monthly payment,and total payment
	private JTextField jtfAnnualInterestRate=new JTextField();
	private JTextField jtfNumberOfYears=new JTextField();
	private JTextField jtfLoanAmount=new JTextField();
	private JTextField jtfMouthlyPayment=new JTextField();
	private JTextField jtfTotalPayment=new JTextField();

	//Create a Compute Payment button
	private JButton jbtComputeLoan=new JButton("Compute Payment");

	public LoanCalculator(){
		//Panel p1 to hold labels and text fields 
		JPanel p1=new JPanel(new GridLayout(5,2));
		p1.add(new JLabel("Annual Interest Rate"));
		p1.add(jtfAnnualInterestRate);
		p1.add(new JLabel("Number of Years"));
		p1.add(jtfNumberOfYears);
		p1.add(new JLabel("Loan Amount"));
		p1.add(jtfLoanAmount);
		p1.add(new JLabel("Mouthly Patment"));
		p1.add(jtfMouthlyPayment);
		p1.add(new JLabel("Total Payment"));
		p1.add(jtfTotalPayment);
		p1.setBorder(new
				TitledBorder("Enter loan amount,interest rate and year") );

		//Panel p2=new to hold the button 
		JPanel p2=new JPanel(new FlowLayout(FlowLayout.RIGHT));
		p2.add(jbtComputeLoan);

		//Add the panels to the frame
		add(p1,BorderLayout.CENTER);
		add(p2,BorderLayout.SOUTH);

		//Register listener
		jbtComputeLoan.addActionListener(new ButtonListener());
	}

	/**Handle the Compute Payment button*/
	private class ButtonListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			//Get values from text fields
			double interest =
					Double.parseDouble(jtfAnnualInterestRate.getText());
			int year =
					Integer.parseInt(jtfNumberOfYears.getText());
			double loanAmount =
					Double.parseDouble(jtfLoanAmount.getText());

			//Create a loan object
			Loan loan =new Loan(interest,year,loanAmount);

			//Display monthly payment and total payment
			jtfMouthlyPayment.setText(String.format("%.2f",
					loan.getMonthlyPayment()));
			jtfTotalPayment.setText(String.format("%.2f",
					loan.getTotalPayment()));
		}
	}

	public static void main(String[] args){
		LoanCalculator frame =new LoanCalculator();
		frame.pack();
		frame.setTitle("LoanCalculator");
		frame.setLocationRelativeTo(null);//Center the frame
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);			
	}
}


 提示:大家在编程时会发现有一个错误——没有Loan类型的定义;现附上该文件Loan.java(http://pan.baidu.com/s/1nt9aOjR),请大家把该文件添加到Java Project(Java工程)中。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值