Solved

Problem detecting JRadioButton action in Mortgage calculator

Posted on 2006-06-10
3
292 Views
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.
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
 
0
Comment
Question by:ghost8067
  • 2
3 Comments
 
LVL 24

Accepted Solution

by:
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.

;JOOP!
 
0
 

Author Comment

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

Expert Comment

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

;JOOP!
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

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…
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…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

705 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

17 Experts available now in Live!

Get 1:1 Help Now