需要创建一个关闭按钮以关闭应用程序并重置以清除字段并以新数量开始。 我添加的关闭按钮对代码没有太大作用,只是复制addInterest按钮功能。
这是框架
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class InvestmentFrame extends JFrame {
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 250;
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 rateLabel;
private JTextField rateField;
private JButton btnInterest, btnExit;
private JTextArea resultArea;
private double balance;
public InvestmentFrame() {
balance = INITIAL_BALANCE;
resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);
resultArea.setText(balance + "\n");
resultArea.setEditable(false);
this.createTextField();
this.createButton();
this.createPanel();
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createTextField() {
rateLabel = new JLabel("Interest Rate: ");
final int FIELD_WIDTH = 10;
rateField = new JTextField(FIELD_WIDTH);
rateField.setText("" + DEFAULT_RATE);
}
class AddInterestListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
try {
double rate = Double.parseDouble(rateField.getText());
if (rate < 0) {
throw new IllegalArgumentException();
}
double interest = balance * rate / 100;
balance = balance + interest;
resultArea.append(balance + "\n");
} catch (Exception exception) {
JOptionPane.showMessageDialog(null, "Rate is a positive floating-point number.",
"Invalid rate value entered!", JOptionPane.ERROR_MESSAGE);
}
}
}
private class CloseListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private void createButton() {
btnInterest = new JButton("Add Interest");
btnExit = new JButton("Close");
ActionListener listener = new AddInterestListener();
btnInterest.addActionListener(listener);
btnExit.addActionListener(listener);
}
private void createPanel() {
JPanel panel = new JPanel();
panel.add(rateLabel);
panel.add(rateField);
panel.add(btnInterest);
panel.add(btnExit);
JScrollPane scrollPane = new JScrollPane(resultArea);
panel.add(scrollPane);
this.add(panel);
}
}
这是观众
import javax.swing.JFrame;
/**
This program shows the growth of an investment.
*/
public class InvestmentViewer {
public static void main(String[] args)
{
JFrame frame = new InvestmentFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
答案 0 :(得分:1)
您没有在退出按钮中添加关闭侦听器。所以它不会关闭应用程序。
ActionListener listener = new AddInterestListener();
btnInterest.addActionListener(listener);
btnExit.addActionListener(listener);
正确的方法:
btnExit.addActionListener(new CloseListener());