I have two issues with my code:

1.When I run the code the components of the GUI are very large. I have attached a screen shot of what it looks like. I'm not sure how to change the size. I've tried using:
nameOfButton.setSize(12,12); but that doesn't work.

2. I'm new to Java and not sure what statement to use to get information from a text file. I'm creating a GUI calculator and I have to read the interest rates from a text file in the action listener portion of the code. I was told that the annual interest statement was incorrect and i'm not sure what it should be.

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.NumberFormat;
import javax.swing.*;

 * @author 
public class Week5_2 extends JFrame implements ActionListener {

    private Container contentPane = null;
    private JSplitPane split = null;
    private JPanel lfPanel = null;
    private JScrollPane rtPanel = null;
    private JLabel jl_principal;
    private JTextField tf_principal;
    private JLabel jl_menu;
    private JComboBox jcb_menu;
    private JLabel jl_monthlyPayment;
    private JTextField tf_monthlyPayment;
    private JTextArea amortization;
    private JButton submit;
    private JButton reset;
    private JButton exit;
    private String[] comboMenu = {"7 years at 5.35%", "15 years at 5.5%", "30 years at 5.75%"};
    private String[] interestRates;
    private NumberFormat fmt = NumberFormat.getInstance();

        public Week5_2(){

   private void initalize(){
                interestRates = loadInterestRates("loadtest.txt");
		// set up the number formatter

                contentPane = this.getContentPane();
		setTitle(" Mortgage Calculator");
		setSize(800, 600);
		// set top pane with BoxLayout
		contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS));
		// create a splitpane to layout out code
		split = new JSplitPane();
		// make the splitter up and down
		split.setDividerLocation(200); // set the divider a little off from the middle
		//splitpane.setEnabled(false); // locks the divider bar
		// Call the method to load the left side of the split pane
		// load the right side of the split pane
		// add the split pane to the content pane
		contentPane.add(split, null);
   private String [] loadInterestRates(String filename)
        // assumes you have 3 entries in your file
        String [] retval = new String [3];
        int index = 0;

        	File fromFile = new File(filename);
                BufferedReader reader = new BufferedReader(new FileReader(fromFile));
                        String line = reader.readLine();
            while(line != null)
                retval[index] = line;
                line = reader.readLine();
            return retval;
        catch (IOException e)
            return null;

   private void loadRightSide()
		// display amortization chart in Text Area
		rtPanel = new JScrollPane();
		// make the scroll bars always be there
		// create border
		amortization = new JTextArea();
		Font displayFont = new Font("Serif", Font.BOLD, 14);

		// makes text area uneditable

   private void loadLeftSide (){
       lfPanel = new JPanel();
		// add border to panel
		lfPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.SoftBevelBorder.LOWERED));
		//set Grid layout of left panel
		lfPanel.setLayout(new GridLayout(5,2));

                //create labels and set text that appears on label
                jl_principal = new JLabel ("Mortgage Amount");
                jl_menu = new JLabel ("Term and Interest");
                jl_monthlyPayment = new JLabel ("Monthly Payment");

                //create combo box and text fields
                jcb_menu = new JComboBox(comboMenu);
                tf_principal = new JTextField();
                tf_monthlyPayment = new JTextField();

                //create buttons
                submit = new JButton ("Submit");
                //add action listener
                exit = new JButton ("Exit");
                //add action listener
                reset = new JButton ("Reset");
                //add action listener

                //lay out components on pane
                lfPanel.add(new JLabel(""));//empty cell



   public void actionPerformed(ActionEvent e)
            Object source = e.getSource();
            if (source == exit)//enables exit button to operate
            if (source == reset)//enables reset button to operate
            if(source == jcb_menu)//enables combo box to set selection by user
                 double select = (double) jcb_menu.getSelectedIndex();
                 jcb_menu.setSelectedIndex((int) (double) select);
                int years;
                double annualInterest;
                int indexOne = jcb_menu.getSelectedIndex();//gets selected term and interest from combo box

                double monthlyInt;

            if (source == submit)//calculates mortgage when submit button is pushed
                    double principle = Double.parseDouble(tf_principal.getText().trim());
                    if(indexOne == 0)
                        years = 7;
                        String [] selection = interestRates;
                        annualInterest = selection[0].getDouble();
                    if (indexOne == 1)
                        years = 15;
                        String [] selection = interestRates;
                        annualInterest = selection[1].getDouble();
                    if (indexOne == 2)
                        years = 30;
                        String [] selection = interestRates;
                        annualInterest = selection[2].getDouble();

                        monthlyInt = (double) ((annualInterest / 100)/12);

                  Week5_2Cal calc = new Week5_2Cal (principle, years, monthlyInt);

                  if(principle>0&&years>0&&monthlyInt>0){//prevent negative numbers from being used

                       NumberFormat fmt = NumberFormat.getCurrencyInstance();

                      tf_monthlyPayment.setText("" + fmt.format(calc.getMonthlypayment()));//Gets mortgage payment from Calculation class and assigns to payment.
                      amortization.setText(calc.getAmortizationTableAsString());//Gets amortization schedule from Calculation class and assigns to JTextArea
                  } //if set payment
                    }//end index if
                }//ends try
                 catch(NumberFormatException nfe)
                      JOptionPane.showMessageDialog(null, "Please make sure all your entries are numeric!", "USER INPUT ERROR", JOptionPane.ERROR_MESSAGE);
                  } //ends catch
            }//ends submit if
  }//ends action listener

    public static void main(String[] args) {
        Week5_2 w5 = new Week5_2();
    }//ends main

}//ends class

You have defined many String[] selection as local variables. When execution moves out of the {} enclosing the definition, the variables are no longer defined.
Move the definition of selection out of the methods to where it is in scope for the methods that need it.

Read up on "scope" to understand this concept.

Use a FileReader to read data from files. Do a Search on this forum for sample code that uses that class.

Re all thise String arrays:
Apart from the load method, they are used as temporary variables, so scope is OK. BUT they all seem to be redundant, eg

String [] selection = interestRates;
annualInterest = selection[1].getDouble();

why not just

annualInterest = interestRates[1].getDouble();

Thanks! The only problem is even if I use

annualInterest = interestRates[1].getDouble();

the compiler shows it as an error that says "cannot find method getDouble();". I'm not sure what is missing.

You used the getDouble() method in your earlier code. Did you have a problem compiling that?

There is no method getDouble in the String class, so I don't see how it could have worked in the original case either.

Were you trying to get to this maybe?

annualInterest = Double.parseDouble(interestRates[1]);

Also the Array class has a getDouble() method:
= Array.getDouble(interestRates, 1);

Good programming practice recommends that the data be edited on input and stored as a double vs storing a String and continually parsing it.

You used the getDouble() method in your earlier code. Did you have a problem compiling that?

Yes, I got the same error in the code I posted earlier.

Edited 6 Years Ago by SashaC: n/a

Ok. Look at the preceding two posts and choose a method to convert the Strings you read from the file to the double you need to do the math.

.When I run the code the components of the GUI are very large

How could you run the code if it doesn't compile?

Edited 6 Years Ago by NormR1: n/a

When I press submit, the calculator doesn't work. I'm not sure if it's a problem with my calculation or reading from my text file. This is a class assignment so just let me know what information I may need to review to figure this out.

Ok. Look at the preceding two posts and choose a method to convert the Strings you read from the file to the double you need to do the math.

How could you run the code if it doesn't compile?

I wanted to see how it looked so I turned the calculation portion of the code into comments so that it could compile.

Debugging 101:

Put lots of System,out.println statements into your code so you can see whether or not variables are being set as you expected - eg while reading from the text file, print what you read, when converting to float print the result, when doing all thise "if" tests in the calculator print a line to show which one was executed, etc etc. That way you can see where its going wrong.

This article has been dead for over six months. Start a new discussion instead.