Problem detecting JRadioButton action in Mortgage calculator

I am having difficulty getting the changes to radio buttons being detected. I have the user interface looking correct and tried using isSelected to tell which radio button is chosen. When a change is detected, I want the program to assign the values in the term and yearlyRate variabes according to that radio button selection. I tried using the same if statements in the area of my math calcculation, but i get an error that says the aButton etc. cannot be found. I thought this might work if the variables were updated just before doing the calculation. I am having a second problem with my calculation. Although the math was working correctly when I got input from the user in the previous version, it looks like when I assign the variables directly I am getting the wrong answer. Anyway, if I can get some help with the radio buttons, I can work on figuring out the problem with the math.
Any aqssistance would be greatly appreciated.
Jon

My code is below.


/* Mortgage Monyhly Payment Calculator with graphical user interface
Programmer:  J.Schab
Date:        June 4,2006
Filename:    Mortgage.java
Purpose:     This project accepts the mortgage amount and gives the user a choice of 3 loan types through the use of radio buttons. The program then calculates the monthly mortgage payment and displays it in currency format.
There is a quit button to exit the application, and a clear button to clear user entered fields in order to calculate a new mortgage. The program will also clear the payment field should the user press any key while positioned
in any input textfield.


 */



import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JScrollPane.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.text.NumberFormat;
import java.util.Locale;
import java.text.*;

class Mortgage extends JFrame
{


     int term = 0;
     double yearlyRate = 0.00;        


    private JLabel headerJLabel;

    Border rowborder = new EmptyBorder( 3, 10, 3, 10 );
    String titles = "Month \t Principal\t Interest\tBalance\n";        

    // JLabel and JTextField for the mortgage amount
    private JLabel amountJLabel;
    private JTextField amountJTextField;

    // JLabel for monthly mortgage payment
    private JLabel monthpayJLabel;

    // JTextArea for displaying payment
    private JTextArea outputJTextArea;

   
    // JButton to initiate calculations
    private JButton calculateJButton;

    // JButton to clear entries
    private JButton clearJButton;

    // JButton to quit
    private JButton quitJButton;
   

    // no-argument constructor    
    public Mortgage()

     
   
    {
        createUserInterface();
    }

    // create and position the GUI components; register event handlers
    private void createUserInterface()
    {
        // get content pane for attaching GUI components
        Container contentPane = getContentPane();

        JTextArea displayArea = new JTextArea(10, 45);
        JScrollPane scroll = new JScrollPane(displayArea);

       
        setTitle("Mortgage Calculator"); // set title bar text


        // set northLabel using borderlayout
        headerJLabel = new JLabel();
        headerJLabel.setBounds(10, 1, 300, 46);
        headerJLabel.setText("Enter a mortgage amount and select a loan");
        contentPane.add(headerJLabel);

        // enable specific positioning of GUI components
        contentPane.setLayout(null);

        // set up amountJLabel
        amountJLabel = new JLabel();
        amountJLabel.setBounds(76, 36, 104, 26);
        amountJLabel.setText("Mortgage amount:");
        contentPane.add(amountJLabel);

        // set up amountJTextField
        amountJTextField = new JTextField();
        amountJTextField.setBounds(200, 36, 56, 26);
        amountJTextField.setHorizontalAlignment(JTextField.RIGHT);
        contentPane.add(amountJTextField);
        amountJTextField.addKeyListener(

        new KeyAdapter() // anonymous inner class
        {
            // event handler for key pressed in amountJTextField
            public void keyPressed(KeyEvent event)
            {
                amountJTextFieldkeyPressed(event);
            }

        } // end anonymous inner class

        ); // end call to addKeyListener

    // added code below for radio buttons

        JPanel radioPanel = new JPanel();
               JRadioButton aButton = new JRadioButton("7 Years at 5.35%" , true);
               JRadioButton bButton = new JRadioButton("15 Years at 5.50%" , false);
               JRadioButton cButton = new JRadioButton("30 Years at 5.75%", false);


        ButtonGroup bgroup = new ButtonGroup();      
          bgroup.add(aButton);
          bgroup.add(bButton);
          bgroup.add(cButton);
          radioPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4 ));      
          radioPanel.add(aButton);
          radioPanel.add(bButton);
          radioPanel.add(cButton);
          contentPane.add(radioPanel);
          //radioPanel.setMaximumSize( new Dimension( 10000, radioPanel.getMinimumSize().height ) );
          radioPanel.setBorder( rowborder );
          radioPanel.setBounds( 90, 56, 195, 95 );
         
          if (aButton.isSelected()){
             term = 7;
             yearlyRate = 5.35;
          }
         
         
          if (bButton.isSelected()){
             term = 15;
             yearlyRate = 5.50;
          }
         
         
          if (cButton.isSelected()){
             term = 30;
             yearlyRate = 5.75;
          }

     
         
        // set up calculateJButton
        calculateJButton = new JButton();
        calculateJButton.setBounds(26, 320, 90, 26);
        calculateJButton.setText("Calculate");
        contentPane.add(calculateJButton);
        calculateJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when calculateJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                calculateJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener

        // set up clearJButton
        clearJButton = new JButton();
        clearJButton.setBounds(136, 320, 90, 26);
        clearJButton.setText("Clear");
        contentPane.add(clearJButton);
        clearJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when clearJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                clearJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up quitJButton
        quitJButton = new JButton();
        quitJButton.setBounds(250, 320, 90, 26);
        quitJButton.setText("Quit");
        contentPane.add(quitJButton);
        quitJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when quitJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                quitJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up outputJTextArea
        outputJTextArea = new JTextArea();
        contentPane.add(outputJTextArea);
        outputJTextArea.setBounds(200, 146, 56, 26);
        outputJTextArea.setEditable(false);

        //set up monthpayJLabel
        monthpayJLabel = new JLabel();
        monthpayJLabel.setBounds(76, 146, 156, 26);
        monthpayJLabel.setText("Monthly Payment:");
        contentPane.add(monthpayJLabel);

        scroll.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
        contentPane.add(scroll);
        scroll.setBounds(20, 186, 356, 130);
        setVisible(true);
        displayArea.setText(titles);
         

       
              
    } // end method createUserInterface

    // called when user presses key in amountJTextField
    private void amountJTextFieldkeyPressed(KeyEvent event)
    {
        outputJTextArea.setText(""); // clear outputJTextArea
    }

        // method called when user clicks calculateJButton
    private void calculateJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            //int term = Integer.parseInt(termJTextField.getText());
                // length of the loan in years
            int monthCount = (term * 12); // Calculate months from years
            int amount = Integer.parseInt(amountJTextField.getText());
            //double yearlyRate = Double.parseDouble(interestJTextField.getText())
            //    ;
            double interestRateMonthly = (yearlyRate / 12) / 100;
                // Calculate monthly interest
            double monthlyPayment; // monthly payment amount variable

            // Calculate monthly payment
            monthlyPayment = (amount * interestRateMonthly) / (1-Math.pow(1 +
                interestRateMonthly,  - monthCount));



            DecimalFormat currency = new DecimalFormat("$0.00");
                // Format output
            outputJTextArea.setText(currency.format(monthlyPayment));
                // Output payment amount

        }
        catch (NumberFormatException ex){}
    }


    // method called when user clicks clearJButton
    private void clearJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            outputJTextArea.setText(""); // clear outputJTextArea
            amountJTextField.setText(""); // clear amountJTextField
            //interestJTextField.setText(""); // clear interestJTextField
            //termJTextField.setText(""); // clear termJTextField

        }
        catch (NumberFormatException ex){}
    }





    // method called when user clicks quitJButton
    private void quitJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            System.exit(0);

        }
        catch (NumberFormatException ex){}
    }



    // main method
    public static void main(String[]args)
    {
        Mortgage application = new Mortgage();
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        application.setSize(400, 400);
        application.setVisible(true);
    } // end method main

} // end class Mortgage
 
ghost8067Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
sciuriwareConnect With a Mentor Commented:
              JRadioButton aButton = new JRadioButton("7 Years at 5.35%" , true);
               JRadioButton bButton = new JRadioButton("15 Years at 5.50%" , false);
               JRadioButton cButton = new JRadioButton("30 Years at 5.75%", false);

These buttons are local to
               private void createUserInterface()

So they will disappear upon return and can't be accessed from outside.

Add them to the other buttons.

;JOOP!
 
0
 
ghost8067Author Commented:
Thanks so much for the help. It is working like a charm. This also corrected the math issue.
Have a great day.
Jon
0
 
sciuriwareCommented:
At your service; success with your study.

;JOOP!
0
All Courses

From novice to tech pro — start learning today.