获取在JPanel

时间:2015-05-22 10:05:07

标签: java swing methods jpanel jtextarea

所以我正在为一个班级的项目工作,因为我正在努力学习这个叫做Java的可爱的东西。好吧无论如何我试图在我的JPanel中的TextArea中打印出一些方法。

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");
}
}

我已经发现下面的行是问题所在,我尝试了许多不同的方法来使其工作。我有点在我的智慧结束。我已经阅读了很多关于发送到textArea但很难找到方法的东西。请帮助或至少向我发送正确的方向。非常感谢。这是问题区域:

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

更新 我通过扩展你们给我的想法来实现它,我还添加了一个滚动窗格。滚动条没有显示,所以如果有人可以给我一些建议,为什么滚动窗格不能正常工作。

滚动窗格以外的新工作代码:

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");

}
}

2 个答案:

答案 0 :(得分:5)

您的代码中出现了一些问题:

  • 使用JTextArea而不是TextArea(所以一切都是Swing)
  • 未使用字段calculation,因为您在代码中创建了一个新的局部变量TextArea calculation = new TextArea();
  • String txtLoanAmount = textLoanAmount.getText();等局部变量无用! txtLoanAmount 是对textLoanAmount内容的永久引用。它只是此时文本字段内容的快照(即“”,因为您刚刚创建了文本字段)。
  • 您的calcAmortization()方法是正确的,但它打印到标准输出,而不打印到计算文本区域,也不打印到可以附加到文本区域的字符串。所以我只是将标准输出重定向到您的文本区域,尽可能少地重写代码。
  • 您应该使用真实的布局,例如null(我没有修复),而不是在每个组件上使用setBound()布局和GridBagLayout

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");
    }
}

请注意这一位,它会使用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());
    }

}));

答案 1 :(得分:0)

这里有你在构造函数中声明的变量txtLoanAmount,txtYears,txtInterestRate等。因此它们仅存在于声明它们的函数范围内。但是你在另一个类中使用那些变量,这没有意义,

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

这是匿名课程。因为它没有名字。

所以你应该做以下事情,

  1. 将这些变量声明为final。或
  2. 通过在构造函数之外声明它们来使它们成为实例变量。