获取打印到 JPanel 中的 TextArea 的方法

Getting methods to print to a TextArea in JPanel

所以我正在为 class 做一个项目,因为我正在尝试学习这个叫做 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");

}
}

您的代码中有几处错误:

  • 使用 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());
    }

}));

此处是您在构造函数中声明的变量 txtLoanAmount、txtYears、txtInterestRate 等。所以它们只存在于声明它们的函数范围内。但是你在另一个 class 中使用这些变量,这没有意义,

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

这是匿名的 class。因为它没有名字。

因此您应该执行以下操作,

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