I am creating a (well, already created) loan payment calculator using the graphical user interface in Java. Some of the calculations are wrong, and I will correct them, so do not pay attention to them. What I really need is a user input validation. I tried using the try / catch block, but on NetBeans I am all blushing where the catch exception is. Why am I getting underscores and is this the correct type of check? Let me know if more code or information is required. Here is the main class / driver code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class LoanCalculator extends JFrame {
private static final JTextField INTEREST_RATE = new JTextField();
private static final JTextField LOAN_YEARS = new JTextField();
private static final JTextField LOAN_AMOUNT = new JTextField();
private static final JTextField MONTHLY_PAYMENT = new JTextField();
private static final JTextField TOTAL_PAYMENT = new JTextField();
private static final JButton LOAN_COMPUTE = new JButton("Compute Payment");
public LoanCalculator() {
JPanel labelPanel = new JPanel(new GridLayout(6, 2));
labelPanel.add(new JLabel("Annual Interest Rate"));
labelPanel.add(INTEREST_RATE);
labelPanel.add(new JLabel("Number of Years"));
labelPanel.add(LOAN_YEARS);
labelPanel.add(new JLabel("Loan Amount"));
labelPanel.add(LOAN_AMOUNT);
labelPanel.add(new JLabel("Monthly Payment"));
labelPanel.add(MONTHLY_PAYMENT);
labelPanel.add(new JLabel("Total Payment"));
labelPanel.add(TOTAL_PAYMENT);
labelPanel.setBorder(new TitledBorder("Enter loan amount, interest rate, and years"));
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonPanel.add(LOAN_COMPUTE);
add(labelPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
LOAN_COMPUTE.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try{
double interest = Double.parseDouble(INTEREST_RATE.getText());
int year = Integer.parseInt(LOAN_YEARS.getText());
double loanAmount = Double.parseDouble(LOAN_AMOUNT.getText());
Loan loan = new Loan(interest, year, loanAmount);
MONTHLY_PAYMENT.setText(String.format("%.2f", loan.getMonthlyPayment()));
TOTAL_PAYMENT.setText(String.format("%.2f", loan.getTotalPayment()));
}catch (Exception ex){
JOptionPane.showMessageDialog(this, ex.getMessage(), "Error," , JOptionPane.ERROR_MESSAGE));
}
}
}
public static void main(String[] args) {
LoanCalculator frame = new LoanCalculator();
frame.pack();
frame.setTitle("LoanCalculator");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
source
share