4

So I am working on a project for a class because I am trying to learn this lovely thing called Java. Well anyway I am trying to get some methods to print out in the TextArea in my JPanel.

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;



public class GUI_Amortization_Calculator extends JFrame {

private JPanel contentPane;
private JTextField textLoanAmount;
private JTextField textYears;
private JTextField textInterestRate;
TextArea calculation;
/**
 * @wbp.nonvisual location=71,9
 */
/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GUI_Amortization_Calculator frame = new GUI_Amortization_Calculator();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public GUI_Amortization_Calculator() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 650, 600);
    getContentPane().setLayout(null);

    JPanel panel_2 = new JPanel();
    panel_2.setBounds(10, 11, 614, 34);
    getContentPane().add(panel_2);

    JLabel IntroLabel = new JLabel("Introduction to Java Class GUI Amortization Mortgage Calculator by Beth Pizana");
    IntroLabel.setForeground(Color.MAGENTA);
    IntroLabel.setFont(new Font("Arial Black", Font.BOLD, 12));
    panel_2.add(IntroLabel);

    JPanel panel = new JPanel();
    panel.setBounds(10, 56, 198, 495);
    getContentPane().add(panel);

    JLabel loanAmountLabel = new JLabel("Enter your loan amount:");
    loanAmountLabel.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(loanAmountLabel);

    textLoanAmount = new JTextField();
    textLoanAmount.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(textLoanAmount);
    textLoanAmount.setColumns(15);
    String txtLoanAmount = textLoanAmount.getText();

    JLabel yearsLabel = new JLabel("Enter the years of your loan:");
    yearsLabel.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(yearsLabel);

    textYears = new JTextField();
    textYears.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(textYears);
    textYears.setColumns(15);
    String txtYears = textYears.getText();

    JLabel interestRateLavel = new JLabel("Enter the interest rate of your loan:");
    interestRateLavel.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(interestRateLavel);

    textInterestRate = new JTextField();
    textInterestRate.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(textInterestRate);
    textInterestRate.setColumns(15);
    String txtInterestRate = textInterestRate.getText();

    JButton calculate = new JButton("Calculate");
    calculate.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            Double loanAmount = Double.parseDouble(txtLoanAmount);
            int years = Integer.parseInt(txtYears);
            Double interestRate = Double.parseDouble(txtInterestRate);
            String calc  = calculation.getText(calcAmortization(loanAmount, years, interestRate));
            textarea.append(calc);

        }
    });

    calculate.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(calculate);

    JButton reset = new JButton("Reset");
    reset.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            textLoanAmount.setText("");
            textYears.setText("");
            textInterestRate.setText("");
        }
    });
    reset.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(reset);

    TextArea calculation = new TextArea();

    calculation.setColumns(6);
    calculation.setBounds(228, 51, 380, 500);
    getContentPane().add(calculation);

    JScrollBar scrollBar = new JScrollBar();
    scrollBar.setBounds(591, 56, 17, 477);
    getContentPane().add(scrollBar);

    JScrollBar scrollBar_1 = new JScrollBar();
    scrollBar_1.setOrientation(JScrollBar.HORIZONTAL);
    scrollBar_1.setBounds(231, 534, 363, 17);
    getContentPane().add(scrollBar_1);


}
public static void calcAmortization(double loanAmount, int numYears, double interestRate){
    double newBalance;
    //Calculate the monthly interest rate
    double monthlyInterestRate = (interestRate / 12)/100;
    //Calculate the number of months
    int totalMonths = numYears * 12;
    double monthlyPayment, interestPayment, principalPayment;
    int count;

    //Calculate the monthly payment
    monthlyPayment = loanAmount * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, (double)totalMonths)/(Math.pow(1 + monthlyInterestRate, (double)totalMonths)-1);

    printTableHeader();

    for (count = 1; count < totalMonths; count++){
        interestPayment = loanAmount * monthlyInterestRate;
        principalPayment = monthlyPayment - interestPayment;
        newBalance = loanAmount - principalPayment;
        printSchedule(count, loanAmount, monthlyPayment, interestPayment, principalPayment, newBalance);
        loanAmount = newBalance;
    }
}
public static void printSchedule(int count, double loanAmount, double monthlyPayment, double interestPayment, double principalPayment, double newBalance){

    System.out.format("%-8d$%,-12.2f$%,-10.2f$%,-10.2f$%,-10.2f$%,-12.2f\n",count,loanAmount,monthlyPayment,interestPayment,principalPayment,newBalance);

}
public static void printTableHeader(){
    int count;
    System.out.println("\nAmortization Schedule for  Borrower");
    for(count=0;count<62;count++) System.out.print("-");
        System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s"," ","Old","Monthly","Interest","Principal","New","Balance");
        System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s\n\n","Month","Balance","Payment","Paid","Paid","Balance");
}
}

I have already figured out that the lines below are the problem and I have tried a number of different ways to make it work. I am sort of at my wits end. I have read a number things about sending to the textArea but having difficulty finding ones with methods. Please help or at least send me in the right direction. Thanks very much. Here is the problem area:

    String calc  = calculation.getText(calcAmortization(loanAmount, years, interestRate));
    textarea.append(calc);

Update I got it working by expanding on the ideas you guys gave me and I also added a Scroll Pane. The scroll bar is not showing up so if anyone can give me some advice as to why the scroll pane is not working properly.

New working code except the scroll pane:

import java.awt.*;
import javax.swing.*;    
import java.awt.event.*;
import java.io.*;

@SuppressWarnings("serial")
public class GUI_Amortization_Calculator extends JFrame {

private JPanel contentPane;
private JTextField textLoanAmount;
private JTextField textYears;
private JTextField textInterestRate;
//private JTextArea calculation;
private PrintStream standardOut;
/**
 * @wbp.nonvisual location=71,9
 */
/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GUI_Amortization_Calculator frame = new GUI_Amortization_Calculator();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
/**
 * Create the frame.
 */
public GUI_Amortization_Calculator() {

    class SpecialOutput extends OutputStream {
        private JTextArea calculation;

        public SpecialOutput(JTextArea calculation) {
            this.calculation = calculation;
        }

        @Override
        public void write(int b) throws IOException {
            // redirects data to the text area
            calculation.append(String.valueOf((char)b));
            // scrolls the text area to the end of data
            calculation.setCaretPosition(calculation.getDocument().getLength());
        };

    }

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 950, 650);
    getContentPane().setLayout(null);

    JPanel panel_2 = new JPanel();
    panel_2.setBounds(10, 11, 614, 34);
    getContentPane().add(panel_2);

    JLabel IntroLabel = new JLabel("Introduction to Java Class GUI Amortization Mortgage Calculator by Beth Pizana");
    IntroLabel.setForeground(Color.MAGENTA);
    IntroLabel.setFont(new Font("Arial Black", Font.BOLD, 12));
    panel_2.add(IntroLabel);

    JPanel panel = new JPanel();
    panel.setBounds(10, 56, 198, 545);
    getContentPane().add(panel);

    JLabel loanAmountLabel = new JLabel("Enter your loan amount:");
    loanAmountLabel.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(loanAmountLabel);

    JTextField textLoanAmount = new JTextField();
    textLoanAmount.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(textLoanAmount);
    textLoanAmount.setColumns(15);
    //String txtLoanAmount = textLoanAmount.getText();

    JLabel yearsLabel = new JLabel("Enter the years of your loan:");
    yearsLabel.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(yearsLabel);

    JTextField textYears = new JTextField();
    textYears.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(textYears);
    textYears.setColumns(15);
    //String txtYears = textYears.getText();

    JLabel interestRateLavel = new JLabel("Enter the interest rate of your loan:");
    interestRateLavel.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(interestRateLavel);

    JTextField textInterestRate = new JTextField();
    textInterestRate.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(textInterestRate);
    textInterestRate.setColumns(15);
    //String txtInterestRate = textInterestRate.getText();

    JButton calculate = new JButton("Calculate");
    calculate.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            double loanAmount = Double.parseDouble(textLoanAmount.getText());
            int years = Integer.parseInt(textYears.getText());
            double interestRate = Double.parseDouble(textInterestRate.getText());
            calcAmortization(loanAmount, years, interestRate);
            //String calc  = calculation.getText();
            //calculation.append(calc);

        }
    });


    calculate.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(calculate);

    JButton reset = new JButton("Reset");
    reset.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            textLoanAmount.setText(null);
            textYears.setText(null);
            textInterestRate.setText(null);
        }
    });
    reset.setFont(new Font("Arial", Font.PLAIN, 12));
    panel.add(reset);


    JTextArea calculation = new JTextArea();
    calculation.setBounds(228, 51, 680, 550);
    PrintStream printStream = new PrintStream(new SpecialOutput(calculation));
    getContentPane().add(calculation);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setBounds(228, 51, 680, 550);
    getContentPane().add(scrollPane);
    standardOut = System.out;
    System.setOut(printStream);
    System.setErr(printStream);

}
public static void calcAmortization(double loanAmount, int numYears, double interestRate){
    double newBalance;
    //Calculate the monthly interest rate
    double monthlyInterestRate = (interestRate / 12)/100;
    //Calculate the number of months
    int totalMonths = numYears * 12;
    double monthlyPayment, interestPayment, principalPayment;
    int count;

    //Calculate the monthly payment
    monthlyPayment = loanAmount * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, (double)totalMonths)/(Math.pow(1 + monthlyInterestRate, (double)totalMonths)-1);

    printTableHeader();

    for (count = 1; count < totalMonths; count++){
        interestPayment = loanAmount * monthlyInterestRate;
        principalPayment = monthlyPayment - interestPayment;
        newBalance = loanAmount - principalPayment;
        printSchedule(count, loanAmount, monthlyPayment, interestPayment, principalPayment, newBalance);
        loanAmount = newBalance;
    }
}
public static void printSchedule(int count, double loanAmount, double monthlyPayment, double interestPayment, double principalPayment, double newBalance){

    System.out.format("%-8d$%,-12.2f$%,-10.2f$%,-10.2f$%,-10.2f$%,-12.2f\n",count,loanAmount,monthlyPayment,interestPayment,principalPayment,newBalance);

}
public static void printTableHeader(){
    int count;
    System.out.println("\nAmortization Schedule for  Borrower");
    for(count=0;count<62;count++) System.out.print("-");
        System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s"," ","Old","Monthly","Interest","Principal","New","Balance");
        System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s\n\n","Month","Balance","Payment","Paid","Paid","Balance");

}
}
  • You don't "print" to a JTextArea, you just "set" the text. So, you have managed to deduce those lines cause "the problem". The first thing we require to be able to help, is to know what "the problem" actually is. Can you be a bit more specific about that? – Stultuske May 22 '15 at 10:07
  • `String calc = calculation.getText(calcAmortization(loanAmount, years, interestRate));` I figured out what was wrong with the second line it needed to be `calculation.append(calc);` The error I am getting is that the string line The method getText() in the type TextComponent is not applicable for the arguments (void) I am not sure how to change those methods to still use the getText() I tried just removing the void part and that just gives even more errors. Is there another method I should be using to get the information from those void methods to my TextArea in my JPanel? – morningmist May 22 '15 at 10:15
  • 1
    normally, a getText method does not take any arguments. So, start with this: String calc = calculation.getText(); – Stultuske May 22 '15 at 10:22
  • That is fine but how do I call my methods so they will set their info into the TextArea then. – morningmist May 22 '15 at 10:35
  • 1
    1) Change `TextArea calculation = new TextArea();` to `JTextArea calculation = new JTextArea();` 2) `..setBounds(228, 51, 380, 500);` setBounds(228, 51, 380, 500); Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson May 22 '15 at 11:01
  • 1
    You must not add both `calculation` and `scrollpane` to the content pane. You add calculation to scrollpane, then scrollpane to the content pane. This is what I did in my solution: `JScrollPane p = new JScrollPane(calculation);`, then `p.setBounds(228, 51, 380, 500);` and finally `getContentPane().add(p);` – Eric Leibenguth May 22 '15 at 13:49

2 Answers2

5

A few things were wrong in your code:

  • Use JTextArea instead of TextArea (so everything is Swing)
  • The field calculation was not used, because you created a new local variable in your code TextArea calculation = new TextArea();
  • The local variables such as String txtLoanAmount = textLoanAmount.getText(); are useless! txtLoanAmount is not a permanent reference to the content of textLoanAmount. It is just a snapshot of the content of the text field at this instant (which is: "", because you just created the text field).
  • Your calcAmortization() method is correct, but it prints to standard output, not to the calculation text area, nor to a string that you could append to the text area. So I just redirected the standard output to your text area, to rewrite as little code as possible.
  • Instead of using a null layout and setBound() on each component, you should probably use a real layout, such as GridBagLayout (that, I did not fix).

.

import java.awt.*;    
import javax.swing.*;    
import java.awt.event.*;
import java.io.*;

public class GUI_Amortization_Calculator extends JFrame {

    private JPanel contentPane;
    private JTextField textLoanAmount;
    private JTextField textYears;
    private JTextField textInterestRate;
    private JTextArea calculation;
    /**
     * @wbp.nonvisual location=71,9
     */
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUI_Amortization_Calculator frame = new GUI_Amortization_Calculator();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public GUI_Amortization_Calculator() {

        System.setOut(new PrintStream(new OutputStream(){

            @Override
            public void write(int b) throws IOException {
                // redirects data to the text area
                calculation.append(String.valueOf((char)b));
                // scrolls the text area to the end of data
                calculation.setCaretPosition(calculation.getDocument().getLength());
            }

        }));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 650, 600);
        getContentPane().setLayout(null);

        JPanel panel_2 = new JPanel();
        panel_2.setBounds(10, 11, 614, 34);
        getContentPane().add(panel_2);

        JLabel IntroLabel = new JLabel("Introduction to Java Class GUI Amortization Mortgage Calculator by Beth Pizana");
        IntroLabel.setForeground(Color.MAGENTA);
        IntroLabel.setFont(new Font("Arial Black", Font.BOLD, 12));
        panel_2.add(IntroLabel);

        JPanel panel = new JPanel();
        panel.setBounds(10, 56, 198, 495);
        getContentPane().add(panel);

        JLabel loanAmountLabel = new JLabel("Enter your loan amount:");
        loanAmountLabel.setFont(new Font("Arial", Font.PLAIN, 12));
        panel.add(loanAmountLabel);

        textLoanAmount = new JTextField();
        textLoanAmount.setFont(new Font("Arial", Font.PLAIN, 12));
        panel.add(textLoanAmount);
        textLoanAmount.setColumns(15);
        //String txtLoanAmount = textLoanAmount.getText();

        JLabel yearsLabel = new JLabel("Enter the years of your loan:");
        yearsLabel.setFont(new Font("Arial", Font.PLAIN, 12));
        panel.add(yearsLabel);

        textYears = new JTextField();
        textYears.setFont(new Font("Arial", Font.PLAIN, 12));
        panel.add(textYears);
        textYears.setColumns(15);
        //String txtYears = textYears.getText();

        JLabel interestRateLavel = new JLabel("Enter the interest rate of your loan:");
        interestRateLavel.setFont(new Font("Arial", Font.PLAIN, 12));
        panel.add(interestRateLavel);

        textInterestRate = new JTextField();
        textInterestRate.setFont(new Font("Arial", Font.PLAIN, 12));
        panel.add(textInterestRate);
        textInterestRate.setColumns(15);
        //String txtInterestRate = textInterestRate.getText();

        JButton calculate = new JButton("Calculate");
        calculate.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                Double loanAmount = Double.parseDouble(textLoanAmount.getText());
                int years = Integer.parseInt(textYears.getText());
                Double interestRate = Double.parseDouble(textInterestRate.getText());
                //String calc  = calculation.getText();
                calcAmortization(loanAmount, years, interestRate);
                //textarea.append(calc);

            }
        });

        calculate.setFont(new Font("Arial", Font.PLAIN, 12));
        panel.add(calculate);

        JButton reset = new JButton("Reset");
        reset.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                textLoanAmount.setText("");
                textYears.setText("");
                textInterestRate.setText("");
            }
        });
        reset.setFont(new Font("Arial", Font.PLAIN, 12));
        panel.add(reset);

        calculation = new JTextArea();

        calculation.setColumns(6);
        JScrollPane p = new JScrollPane(calculation);
        p.setBounds(228, 51, 380, 500);
        getContentPane().add(p);

    }
    public static void calcAmortization(double loanAmount, int numYears, double interestRate){
        double newBalance;
        //Calculate the monthly interest rate
        double monthlyInterestRate = (interestRate / 12)/100;
        //Calculate the number of months
        int totalMonths = numYears * 12;
        double monthlyPayment, interestPayment, principalPayment;
        int count;

        //Calculate the monthly payment
        monthlyPayment = loanAmount * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, (double)totalMonths)/(Math.pow(1 + monthlyInterestRate, (double)totalMonths)-1);

        printTableHeader();

        for (count = 1; count < totalMonths; count++){
            interestPayment = loanAmount * monthlyInterestRate;
            principalPayment = monthlyPayment - interestPayment;
            newBalance = loanAmount - principalPayment;
            printSchedule(count, loanAmount, monthlyPayment, interestPayment, principalPayment, newBalance);
            loanAmount = newBalance;
        }
    }
    public static void printSchedule(int count, double loanAmount, double monthlyPayment, double interestPayment, double principalPayment, double newBalance){

        System.out.format("%-8d$%,-12.2f$%,-10.2f$%,-10.2f$%,-10.2f$%,-12.2f\n",count,loanAmount,monthlyPayment,interestPayment,principalPayment,newBalance);

    }
    public static void printTableHeader(){
        int count;
        System.out.println("\nAmortization Schedule for  Borrower");
        for(count=0;count<62;count++) System.out.print("-");
        System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s"," ","Old","Monthly","Interest","Principal","New","Balance");
        System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s\n\n","Month","Balance","Payment","Paid","Paid","Balance");
    }
}

Notice this bit, which redirects everything your print with System.out.print():

System.setOut(new PrintStream(new OutputStream(){

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        calculation.append(String.valueOf((char)b));
        // scrolls the text area to the end of data
        calculation.setCaretPosition(calculation.getDocument().getLength());
    }

}));
Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51
0

Here variables txtLoanAmount, txtYears, txtInterestRate etc you have declared in the constructor. So they exists only in the scope of the function where they are declared. But u are using those variable inside another class, which does not make sense,

calculate.addMouseListener(new MouseAdapter() { // anonymous class @Override public void mousePressed(MouseEvent e) { } });

This is anonymous class. Because it has no name.

So you should do the following,

  1. declare those variables final. or
  2. make them instance variables by declaring them outside of the constructor.
ChanOnly123
  • 1,004
  • 10
  • 12