//v 1.3 import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.text.DecimalFormat; public class LoanPayment implements ActionListener { JFrame loanPayFrame; JPanel loanPayPanel; JTextField loan, years, interestRate; JLabel loanLabel, yearsLabel, intRateLabel, resultLabel; JButton calculate; // Constructor public LoanPayment() { // Create the frame and container. loanPayFrame = new JFrame("銀貸清償計算系統 周國華設計"); loanPayPanel = new JPanel(); loanPayPanel.setLayout(new GridLayout(4, 2)); // Add the widgets. addWidgets(); // Add the panel to the frame. loanPayFrame.getContentPane().add(loanPayPanel, BorderLayout.CENTER); // Exit when the window is closed. loanPayFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Show the converter. loanPayFrame.pack(); loanPayFrame.setVisible(true); } // Create and add the widgets for converter. private void addWidgets() { // Create widgets. loan = new JTextField(14); years = new JTextField(14); interestRate = new JTextField(14); loanLabel = new JLabel("貸款總金額 (例:$3,500,000,請填入3500000)", SwingConstants.LEFT); yearsLabel = new JLabel("貸款總年數 (例:貸款二十年,請填入20)", SwingConstants.LEFT); intRateLabel = new JLabel("貸款年利率 (例:12.5%,請填入12.5)", SwingConstants.LEFT); calculate = new JButton("計算>>"); resultLabel = new JLabel("每月攤還...", SwingConstants.LEFT); // Listen to events from Convert button. calculate.addActionListener(this); // Add widgets to container. loanPayPanel.add(loanLabel); loanPayPanel.add(loan); loanPayPanel.add(yearsLabel); loanPayPanel.add(years); loanPayPanel.add(intRateLabel); loanPayPanel.add(interestRate); loanPayPanel.add(calculate); loanPayPanel.add(resultLabel); loanLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); yearsLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); intRateLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); resultLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); } // Implementation of ActionListener interface. public void actionPerformed(ActionEvent event) { // 計算每月攤還金額 double monthRate = (Double.parseDouble(interestRate.getText())) / 1200; int totalMonth = (Integer.parseInt(years.getText())) * 12; double temp1 = Math.pow(1+monthRate , - totalMonth); double temp2 = (1 - temp1) / monthRate; double result = (Double.parseDouble(loan.getText())) / temp2; DecimalFormat myFormatter = new DecimalFormat("$###,###.##"); String output = myFormatter.format(result); resultLabel.setText("每月攤還" + output); } // main method public static void main(String[] args) { // Set the look and feel. try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) {} LoanPayment pay = new LoanPayment(); } }