我已经正确地重新编码了我的 GUI,其中用户输入了初始余额、年利率和年数。它计算并输出 15 年的数字。IE (10000, 2.5, 5) 正确生成 5 个数字。现在的问题是,用户决定用不同的输入数字再试一次,之前输出的原来的5个数字保留在计算器中,第二次重试输出新的数字。我不确定这是否是它的假设?还是我想清除 5 个原始数字?
这是代码:否则,我对编码很好,只需要澄清一下。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import java.text.DecimalFormat;
public class SavingAccountFrame extends JFrame{
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 500;
private static final int AREA_ROWS = 10;
private static final int AREA_COLUMNS = 30;
private static final double DEFAULT_RATE = 5;
private static final double INITIAL_BALANCE = 1000;
private JLabel amountLabel1;
private JLabel amountLabel2;
private JLabel amountLabel3;
private JTextField amountField1;
private JTextField amountField2;
private JTextField amountField3;
private JButton button;
private JTextArea resultArea;
private JPanel panel;
//private BankAccount account;
public SavingAccountFrame(){
//account = new BankAccount(INITIAL_BALANCE);
resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);
resultArea.setEditable(false);
createTextField();
createButton();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createTextField(){
final int FIELD_WIDTH = 10;
amountLabel1 = new JLabel("Initial Balance: ");
amountField1 = new JTextField(FIELD_WIDTH);
amountField1.setText("" + 100000);
amountLabel2 = new JLabel("Annual Rate: ");
amountField2 = new JTextField(FIELD_WIDTH);
amountField2.setText("" + 3.5);
amountLabel3 = new JLabel("Number of Years: ");
amountField3 = new JTextField(FIELD_WIDTH);
amountField3.setText("" + 15);
}
private void createButton(){
button = new JButton("Calculate");
class AddInterestListener implements ActionListener{
public void actionPerformed(ActionEvent event){
DecimalFormat df = new DecimalFormat("0.00");
double interest;
double balance = Double.parseDouble(amountField1.getText());
double rate = Double.parseDouble(amountField2.getText());
double years = Double.parseDouble(amountField3.getText());
for(int i = 0; i < years; i++){
interest = balance * rate / 100;
balance = balance + interest;
resultArea.append("$" + df.format(balance) + "\n");
}
}
}
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
}
private void createPanel(){
panel = new JPanel();
panel.add(amountLabel1);
panel.add(amountLabel2);
panel.add(amountLabel3);
panel.add(amountField1);
panel.add(amountField2);
panel.add(amountField3);
panel.add(button);
JScrollPane scrollPane = new JScrollPane(resultArea);
panel.add(scrollPane);
add(panel);
}
}