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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
numbers ascending pyramid 101 212
Convert from a json string array to a Java object 3 51
ejb entity bean example 2 7
Problem to Alipay 10 42
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

789 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