Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Problem detecting JRadioButton action in Mortgage calculator

Posted on 2006-06-10
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
LVL 24

Accepted Solution

sciuriware earned 2000 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

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

670 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