I am trying to format my text firlds so that if the user inputs letters or somethings improper, it will display an error message and ask the user to retry entering the number. i am not quite sure where to start with this part. i have the calculator code working and all the buttons. now i am trying to take it a step further. as of now the user can only enter whole number for the code to work but they are able to enter anything they wish until they hit the calculate button. i want to stop them before they get that far. i have not found exactly what i am looking for as of yet and am hoping someone could assist me or point me in the right direction. here is the code:

package bowen.week.pkg2;

import java.text.NumberFormat;
import javax.swing.JOptionPane;


/**
 *
 * @author Joey
 */
public class JoeyWeek2 extends javax.swing.JFrame 
{
    /**
     * Creates new form JoeyWeek2
     */
    public JoeyWeek2() 
    {
        initComponents();



    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        CalcHead = new javax.swing.JLabel();
        PrincipleLabel = new javax.swing.JLabel();
        AprLabel = new javax.swing.JLabel();
        TermLabel = new javax.swing.JLabel();
        InputPrincipleAmt = new javax.swing.JTextField();
        InputAnnualRate = new javax.swing.JTextField();
        InputTermYears = new javax.swing.JTextField();
        CalcButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        MonthlyPmtLabel = new javax.swing.JLabel();
        OutputMonthlyPayment = new javax.swing.JTextField();
        ExitButton = new javax.swing.JButton();
        ResetButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("McBride Financial Mortgage Calculator");
        setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N

        CalcHead.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        CalcHead.setText("McBride Financial Mortgage Calculator");

        PrincipleLabel.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        PrincipleLabel.setText("Principle Amount:");

        AprLabel.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        AprLabel.setText("APR:");

        TermLabel.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        TermLabel.setText("Loan Term (in years):");

        InputPrincipleAmt.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        InputPrincipleAmt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                InputPrincipleAmtActionPerformed(evt);
            }
        });

        InputAnnualRate.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        InputAnnualRate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                InputAnnualRateActionPerformed(evt);
            }
        });

        InputTermYears.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N

        CalcButton.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        CalcButton.setText("Calculate");
        CalcButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CalcButtonActionPerformed(evt);
            }
        });

        MonthlyPmtLabel.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        MonthlyPmtLabel.setText("Monthly Payment:");

        OutputMonthlyPayment.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N

        ExitButton.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        ExitButton.setText("Exit");
        ExitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitButtonActionPerformed(evt);
            }
        });

        ResetButton.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        ResetButton.setText("Reset");
        ResetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("$");

        jLabel2.setText("%");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 169, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(CalcHead, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(109, 109, 109))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(CalcButton)
                        .addGap(241, 241, 241))))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(TermLabel)
                            .addComponent(AprLabel)
                            .addComponent(PrincipleLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(InputTermYears, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(InputPrincipleAmt, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(InputAnnualRate, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(266, 266, 266)
                        .addComponent(ExitButton)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(ResetButton))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(MonthlyPmtLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(OutputMonthlyPayment, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(41, 41, 41))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(CalcHead, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(PrincipleLabel)
                    .addComponent(InputPrincipleAmt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(AprLabel)
                    .addComponent(InputAnnualRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TermLabel)
                    .addComponent(InputTermYears, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CalcButton)
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(MonthlyPmtLabel)
                    .addComponent(OutputMonthlyPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addComponent(ResetButton)
                .addGap(51, 51, 51)
                .addComponent(ExitButton)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void InputAnnualRateActionPerformed(java.awt.event.ActionEvent evt) {                                                
        // TODO add your handling code here:
    }                                               

    private void CalcButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        //The variables involved with the calculation button must be entered-
        // here and defined.

        double MonthlyInterestRate ;
        double TermMonths          ;
        double FormulaNumerator    ;
        double FormulaDenominator  ;
        double MonthlyPayment      ;
        double AnnualRate          ;
        int    TermYears           ;
        double PrincipleAmt        ;

        //This allows the program to transform the "text" entered into -
        // numbers the formula can calculate
        PrincipleAmt   =    Double.parseDouble(InputPrincipleAmt.getText());
        AnnualRate     =    Double.parseDouble(InputAnnualRate.getText());
        TermYears      =    Integer.parseInt(InputTermYears.getText());

        NumberFormat currency = NumberFormat.getCurrencyInstance();

        //calculate term months and monthly interest then
        //formula numerator and denominator and payment

        // calculate payment amount
        // Divide the %interest rate by 100 to return a decimal value
        // Divide the results by 12 to return the monthly interest rate
        MonthlyInterestRate = (AnnualRate / 100) / 12;
        // Multiply the number of years by 12 to return the term in months
        TermMonths = TermYears * 12;
        // Multiply the monthly interest rate by the principle
        FormulaNumerator = (MonthlyInterestRate * PrincipleAmt);
        // Resolve the forumula M=P[i(1+i)to the power n]/[(1+i)to the power of n -1]
        // Use math library, powers function
        FormulaDenominator = 1 -(java.lang.Math.pow((1 + MonthlyInterestRate), (-1 * TermMonths)) );
        MonthlyPayment = FormulaNumerator / FormulaDenominator;





        OutputMonthlyPayment.setText (currency.format(MonthlyPayment));


    }                                          

    private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
       // TODO add your handling code here:
        System.exit(0);
    }                                          

    private void InputPrincipleAmtActionPerformed(java.awt.event.ActionEvent evt) {                                                  
      NumberFormat currency = NumberFormat.getCurrencyInstance();
        InputPrincipleAmt.setText(currency.format(InputPrincipleAmt));

    }                                                 

    private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
       InputPrincipleAmt.setText("");
       InputAnnualRate.setText("");
       InputTermYears.setText("");
       OutputMonthlyPayment.setText("");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JoeyWeek2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JoeyWeek2().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel AprLabel;
    private javax.swing.JButton CalcButton;
    private javax.swing.JLabel CalcHead;
    private javax.swing.JButton ExitButton;
    private javax.swing.JTextField InputAnnualRate;
    private javax.swing.JTextField InputPrincipleAmt;
    private javax.swing.JTextField InputTermYears;
    private javax.swing.JLabel MonthlyPmtLabel;
    private javax.swing.JTextField OutputMonthlyPayment;
    private javax.swing.JLabel PrincipleLabel;
    private javax.swing.JButton ResetButton;
    private javax.swing.JLabel TermLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration
}

Recommended Answers

All 2 Replies

you could add a KeyListener to your textFields to create a reaction on invalid input.

Use a DocumentListener to edit any input to the text field - see the "UpperCaseField" example at the start of the API doc for JTextField.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.