?
Solved

My first little java program

Posted on 2009-02-08
9
Medium Priority
?
178 Views
Last Modified: 2013-11-23
I believe I got this little program to work properly. Just a few things Id like to do but not sure how to do so:

1.) I want to add space between the interest rate row and the row of radio buttons. Also space between the row of radio buttons and the monthly payment row.

2.) Id like to bring the etched border around the radio buttons closer in. Maybe put a title in the etched border too.

3.) When the monthly payment is calculated the color of the text isn't black (hard to read) and I dont know how it got to be the color it is now.

4.) Is there a way to bring in the text fields closer to the labels (principal, term, interest and payment)?  I tried different things but couldn't get it to work.

My goal here is to give the user the option of either choosing to manually fill in the requirements of Principal, term in months and interest rate or fill in the principal amount and select a radio button.  

1.) Is there a way to gray out the radio button options when the user inputs data in the term in months??  then if the user hits calculate without inputting data in the interest rate area have a message indicating to please do so?

2.) If the user selects a radio button, gray out the term in months and the interest rate manual inputs?

Any help would be greatly appreciated!

import java.awt.*;
import java.awt.event.*;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
 
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
 
 
public class mortgageCalc_v6 extends JFrame implements ActionListener 
{
      int months = 0;
      double mortgagedAmount = 0;
      double intRate = 0;
      double monthlyPayment = 0;
      double monthlyInterest = 0;
      int length = 0;
		Border loweredetched;
		
	     public static void main (String[] args) //Main Method
    {
        mortgageCalc_v6 label = new mortgageCalc_v6();
   	  label.setVisible(true);  											//sets the program to be visible
		  label.setTitle("Mortgage Calculator");  						//title of program
        //label.setResizable(false); 										//prevents the program from being resized
        label.setLocation(500, 200);  									//location on screen for program to be placed at
        label.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 	//stops program from running when program is closed out
    }
	 
	 
      String mMonths[] = {"84", "180", "360"};
      String mInterestRate[] = {"5.35", "5.50", "5.75"};
 
      JPanel row1 = new JPanel();
		JLabel mortgageLabel = new JLabel("My First Mortgage Calculator", JLabel.CENTER);
 
      JPanel row2 = new JPanel(new GridLayout(1, 2));
      JLabel labelLoanAmount = new JLabel("Principal ($)",JLabel.LEFT);
      JTextField textFieldLoanAmount = new JTextField(10);
 
      JPanel row3 = new JPanel(new GridLayout(1, 2));
     	JLabel labelLoanTerm = new JLabel("Term in months",JLabel.LEFT);
      JTextField textFieldLoanTerm = new JTextField(10);
 
      JPanel row4 = new JPanel(new GridLayout(1, 2));
      JLabel labelInterestRate = new JLabel("Interest Rate (%)", JLabel.LEFT);
     	JTextField textFieldInterestRate = new JTextField(10);
 
      JPanel row5 = new JPanel(new GridLayout(1, 2));
      JLabel labelMonthlyPayment = new JLabel("Monthly Payment", JLabel.LEFT);
      JTextField textFieldMonthlyPayment = new JTextField(10);
		
		JPanel radioPanel = new JPanel();
		JRadioButton yrButton = new JRadioButton("" , true);
      JRadioButton yr7Button = new JRadioButton("7 Years at 5.35%" , false);
      JRadioButton yr15Button = new JRadioButton("15 Years at 5.50%" , false);
      JRadioButton yr30Button = new JRadioButton("30 Years at 5.75%", false);
 
 
      //create buttons
      JPanel button = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
      JButton amortizeButton = new JButton("Amortization");
      JButton resetCalcs = new JButton("Reset");
      JButton exitButton = new JButton("Exit");
      JButton buttonCalcs = new JButton("Calculate");
 
      //create textarea to diplay payments
      JTextArea displayArea = new JTextArea(10, 40);
      JScrollPane scroll = new JScrollPane(displayArea);
	 
      public mortgageCalc_v6()
      {
            setSize(500, 450);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container panel = getContentPane();
 
            Border rowborder = new EmptyBorder(3, 10, 3, 10);
 
            panel.add(row1);
            row1.add(mortgageLabel);
            row1.setMaximumSize(new Dimension(10000, row1.getMinimumSize().height));
            row1.setBorder(rowborder);
 
            panel.add(row2);
            row2.add(labelLoanAmount);
            row2.add(textFieldLoanAmount);
            row2.setMaximumSize(new Dimension(10000, row2.getMinimumSize().height));
            row2.setBorder(rowborder);
 
            panel.add(row3);
            row3.add(labelLoanTerm);
            row3.add(textFieldLoanTerm);
            row3.setMaximumSize(new Dimension(10000, row3.getMinimumSize().height));
            row3.setBorder(rowborder);
 
            panel.add(row4);
            row4.add(labelInterestRate);
            row4.add(textFieldInterestRate);
            row4.setMaximumSize(new Dimension(10000, row4.getMinimumSize().height));
            row4.setBorder(rowborder);
 
            ButtonGroup year = new ButtonGroup();
				year.add(yrButton);
            year.add(yr7Button);
            year.add(yr15Button);
            year.add(yr30Button);
 
            radioPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 4, 4 ));    
		      radioPanel.add(yr7Button);
            radioPanel.add(yr15Button);
            radioPanel.add(yr30Button);
            panel.add(radioPanel);
            radioPanel.setMaximumSize(new Dimension(10000, radioPanel.getMinimumSize().height));
            //radioPanel.setBorder(rowborder);
				//radioPanel.setBorder(BorderFactory.createLineBorder(Color.black));
  				radioPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
 
            panel.add(row5);
            row5.add(labelMonthlyPayment);
            row5.add(textFieldMonthlyPayment);
            textFieldMonthlyPayment.setEnabled(false);  //set payment amount uneditable
            row5.setMaximumSize(new Dimension(10000, row5.getMinimumSize().height));
            row5.setBorder(rowborder);
 
            button.add(buttonCalcs);
            button.add(resetCalcs);
            button.add(exitButton);
            button.add(amortizeButton);
            panel.add(button);
            button.setMaximumSize(new Dimension(10000, button.getMinimumSize().height));
 
            scroll.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            panel.add(scroll);
 
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            setVisible(true);
            setContentPane(panel);
 
            //add listeners
            resetCalcs.addActionListener(this);
            exitButton.addActionListener(this);
            buttonCalcs.addActionListener(this);
            amortizeButton.addActionListener(this);
				yrButton.addActionListener(this);            
				yr7Button.addActionListener(this);
            yr15Button.addActionListener(this);
            yr30Button.addActionListener(this);
    }
    public void actionPerformed(ActionEvent event)
    {
        Object command = event.getSource();
        if(command == buttonCalcs)
        {
          try
             {
            	mortgagedAmount = Double.parseDouble(textFieldLoanAmount.getText());
        		 }
      	 catch(NumberFormatException e)
        		 {
           		 //catch null pointer exception if Principal is null
                JOptionPane.showMessageDialog(null,"The principal amount must be a positive value and greater than zero!",
                                                   "Warning!", JOptionPane.ERROR_MESSAGE);
        		 }
      	 try
        		 {
            	months = Integer.parseInt(textFieldLoanTerm.getText());
           		intRate = Double.parseDouble(textFieldInterestRate.getText());
         	 }
          catch(NumberFormatException e)
             {
       			 //Set intRate and months based on which item in the combobox is selected
      			 if(yr7Button.isSelected() == true)
       			  {
            	 	 intRate = 5.35;
            		 months = 84;
      		 	  }
      					else if(yr15Button.isSelected() == true)
      			 		{
            				intRate = 5.5;
           					months = 180;
     						}
      					else if (yr30Button.isSelected() == true)
      					{
            				intRate = 5.75;
           					months = 360;
     						}
      					else
      					{
      						//If no button is selected, this is an actual error.  Throw an exception
                        JOptionPane.showMessageDialog(null,"Interest Rate: must be a positive decimal value and greater than zero!\nTerm: must be a positive integer value and greater than zero!\n\t        -OR-        \t\nA Year / Interest Rate option needs to be selected!",
																  			  "Warning!", JOptionPane.ERROR_MESSAGE);
     						}
               }
              monthlyInterest = intRate / 100 / 12;               //Monthly interst intRate
              length = months;                    //Number of months over which loan is amortized
 
              //calculation formula
              //monthlyPayment = (mortgagedAmount * monthlyInterest) / (1 - Math.pow(1 + monthlyInterest, -length));
				  monthlyPayment = (mortgagedAmount * monthlyInterest) / (1 - 1 / Math.pow((1 + monthlyInterest), length));
 
              //formatting variables
              DecimalFormat df = new DecimalFormat("\u00A4#,###.00"); //currency
              textFieldMonthlyPayment.setText("" + df.format(monthlyPayment));
        }
        if(command == resetCalcs)
        {
		  		 //Set all text fields to blank
             textFieldLoanAmount.setText("");
				 textFieldLoanTerm.setText ("");
				 textFieldInterestRate.setText ("");
             textFieldMonthlyPayment.setText("");
             displayArea.setText("");
				 yrButton.setSelected(true);
        }
        if(command == exitButton)
        {
             System.exit(0);
        }
		  
		  
		  
		  
if (command == amortizeButton)
{
      //Amoritization variables
      double loanBalance = length * monthlyPayment;
		double monthlyInterest = (intRate / 100.0) / 12.0;
      double monthlyInterestPaid = 0;                                //Amount of monthlyInterest paid on the loan
      double monthlyPrincipal = 0;                            		//Amount of mortgagedAmount in each monthly payment
      double currentBalance = mortgagedAmount;                    //runing total of mortgagedAmount after payment
      //String titles = "Month\t Principal\t\tInterest\t\tBalance\n";
		//String titles = "Payment\t Monthly\tPrincipal\tInterest\tOutstanding\n";
		//String titles = "Number\t Payment\tPaid\tPaid\tPrincipal\n";
		String titles = "Payment\t Monthly\t Principal\t Interest\t Outstanding\nNumber\t Payment\t Paid\t Paid\t Principal\n";
		
      displayArea.setText(titles);
      displayArea.append("");                                   //Inserts a blank line
 
 
      //This loop is used to calculate and display the payment schedule information
		for (int counter = 0; counter < length; counter++)
      {                                                    
                     //start outer loop
		monthlyInterestPaid = currentBalance * monthlyInterest;
      monthlyPrincipal = monthlyPayment - monthlyInterestPaid;
      loanBalance = loanBalance - monthlyPayment;
		currentBalance = (currentBalance - monthlyPayment) + monthlyInterestPaid;
 
      //formatting variables
      DecimalFormat df = new DecimalFormat("\u00A4#,###.00"); //currency
 
      displayArea.setCaretPosition(0);
      displayArea.append((counter +1)+"\t"+df.format(monthlyPayment)+"\t"+df.format(monthlyPrincipal)+"\t"
            				  +df.format(monthlyInterestPaid)+"\t"+df.format(currentBalance)+"\n");
      }
 
   //formatting variables
   DecimalFormat df = new DecimalFormat("\u00A4#,###.00"); //currency
}
    }
} //End of program

Open in new window

0
Comment
Question by:Cyber IT
  • 6
  • 3
9 Comments
 
LVL 12

Accepted Solution

by:
basav_com earned 1500 total points
ID: 23584288
(i)  Use setBounds() method to position the compoment at a a particular position.
(ii) Consider tf1 is the is the JTextField object.. if tf1.getText().equals("") ---> Then ask the user to enter the text.
(iii) use setBackground() method to change the component background color.

Go thru this link..for more info
http://java.sun.com/docs/books/tutorial/uiswing/components/index.html
0
 

Author Comment

by:Cyber IT
ID: 23584339
I believe I may have asked too many questions in this post??  If i did, Im sorry!
0
 

Author Comment

by:Cyber IT
ID: 23584958
I tried using setBounds and it didnt do anything for me... it still stays to the right.

I dont want to change the background of the field... I just want to change the text color so it is visible. I tried the setText to a color but it didnt work.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 12

Expert Comment

by:basav_com
ID: 23585071
use setForeground() method


setBounds()  ---> which layout u r using ?
0
 

Author Comment

by:Cyber IT
ID: 23585142
I set this for the color and it doesnt work.

textFieldMonthlyPayment.setForeground(Color.red);

Im using GridLayout.
0
 

Author Comment

by:Cyber IT
ID: 23585158
the textFieldMonthlyPayment is an uneditable field but I want it to display a different color because right now it is displaying a light color which is hard to read.
0
 
LVL 12

Assisted Solution

by:basav_com
basav_com earned 1500 total points
ID: 23585321
           textFieldMonthlyPayment.setForeground(Color.red);    <-------------  See this
            row5.add(textFieldMonthlyPayment);
            //textFieldMonthlyPayment.setEnabled(false);  //set payment amount uneditable   <---- Commented
            textFieldMonthlyPayment.setEditable(false);                       <-------------  See this

See attached pic.

pic1-calc.JPG
0
 

Author Comment

by:Cyber IT
ID: 23585577
Oh geeze... that is what was causing it.  setEditable  instead of setEnabled!  WOW!
Thanks!

How can I bring those text fields closer to the labels??  I tried the setBounds() but I didnt see any change.  Also as you can see the etched border around the radio buttons is from side to side.. id like to bring it closer to the radio buttons. is this possible?
0
 

Author Comment

by:Cyber IT
ID: 23585598
I know I can change the setSize but then I lose one of my radio buttons.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month17 days, 2 hours left to enroll

862 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