Problem detecting JRadioButton action in Mortgage calculator

Posted on 2006-06-10
Last Modified: 2010-03-31
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.

My code is below.

/* Mortgage Monyhly Payment Calculator with graphical user interface
Programmer:  J.Schab
Date:        June 4,2006
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()


    // 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");

        // enable specific positioning of GUI components

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

        // set up amountJTextField
        amountJTextField = new JTextField();
        amountJTextField.setBounds(200, 36, 56, 26);

        new KeyAdapter() // anonymous inner class
            // event handler for key pressed in amountJTextField
            public void keyPressed(KeyEvent 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();      
          radioPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4 ));      
          //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);

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

        } // end anonymous inner class

        ); // end call to addActionListener

        // set up clearJButton
        clearJButton = new JButton();
        clearJButton.setBounds(136, 320, 90, 26);

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

        } // end anonymous inner class

        ); // end call to addActionListener

        // set up quitJButton
        quitJButton = new JButton();
        quitJButton.setBounds(250, 320, 90, 26);

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

        } // end anonymous inner class

        ); // end call to addActionListener

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

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

        scroll.setBounds(20, 186, 356, 130);

    } // 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)
            //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
                // Output payment amount

        catch (NumberFormatException ex){}

    // method called when user clicks clearJButton
    private void clearJButtonActionPerformed(ActionEvent event)
            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)

        catch (NumberFormatException ex){}

    // main method
    public static void main(String[]args)
        Mortgage application = new Mortgage();
        application.setSize(400, 400);
    } // end method main

} // end class Mortgage
Question by:ghost8067
  • 2
LVL 24

Accepted Solution

sciuriware earned 500 total points
ID: 16877066
              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.


Author Comment

ID: 16877236
Thanks so much for the help. It is working like a charm. This also corrected the math issue.
Have a great day.
LVL 24

Expert Comment

ID: 16877357
At your service; success with your study.


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
servlet doXXX methods 3 37
more than one jdk and one jre 1 33
table example 4 23
Opening PDF on button click and fill new document 2 19
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
The viewer will learn how to implement Singleton Design Pattern in Java.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now