所以我创建了一个标准银行账户余额为500的程序。该程序询问用户是否愿意提款或存款,然后计算他们撤回或存入的金额并更新当前余额。为什么它不起作用,我该如何解决?
public class MyFrame extends JFrame {
private JPanel panel;
private JLabel wordsLabel;
private JLabel balanceLabel;
private JLabel choiceLabel;
private JTextField transactionAmount;
private JButton depositButton;
private JButton withdrawButton;
private double balance;
public MyFrame() {
final int FIELD_WIDTH = 10;
balance = 500;
panel = new JPanel();
wordsLabel = new JLabel();
balanceLabel = new JLabel();
choiceLabel = new JLabel();
transactionAmount = new JTextField(FIELD_WIDTH);
JPanel buttonPanel = new JPanel();
ButtonGroup myGroup = new ButtonGroup();
//panel.setLayout(new BorderLayout());
depositButton = new JButton("Deposit");
withdrawButton = new JButton("Withdraw");
transactionAmount.setText("0");
wordsLabel.setText("Welcome to Wes Banco! Your current balance is: ");
balanceLabel.setText("500");
choiceLabel.setText("How much would you like to deposit/withdraw?");
panel.add(wordsLabel);
panel.add(balanceLabel);
panel.add(choiceLabel);
panel.add(transactionAmount);
myGroup.add(depositButton);
myGroup.add(withdrawButton);
buttonPanel.add(depositButton);
buttonPanel.add(withdrawButton);
panel.add(depositButton);
ButtonListener myListener = new ButtonListener();
depositButton.addActionListener(myListener);
withdrawButton.addActionListener(myListener);
panel.add(buttonPanel);
this.add(panel);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double amount = Double.parseDouble(transactionAmount.getText());
if (amount == 0) {
JOptionPane.showMessageDialog(null, "Enter an amount");
}
if (depositButton.isSelected()) {
balanceLabel.setText("" + 500 + amount);
JOptionPane.showMessageDialog(null,
"You have deposited: " + amount);
}
if (withdrawButton.isSelected()) {
}
}
}
}
答案 0 :(得分:2)
您在actionPerformed方法中没有使用正确的“if”。你应该使用:
if (event.getSource() == depositButton) {
//recalculate
}
而不是:
if (depositButton.isSelected()) {
//recalculate
}
isSelected()不是确定是否单击了JButton的正确方法。您必须将点击事件的来源与按钮进行比较。
答案 1 :(得分:2)
有些事情出了问题。
balance
变量(因此多次存款/取款不会生效)。"" + 500 + amount
使用字符串连接,而不是添加。您需要以下内容:
public void actionPerformed(ActionEvent event) {
double amount = Double.parseDouble(transactionAmount.getText());
if (amount == 0) {
JOptionPane.showMessageDialog(null, "Enter an amount");
} else {
if (event.getSource() == depositButton) {
JOptionPane.showMessageDialog(null,
"You have deposited: " + amount);
balance += amount;
} else if (event.getSource() == withdrawButton) {
if (balance < amount) {
JOptionPane.showMessageDialog(null,
"You cannot withdraw more than your balance.");
} else {
JOptionPane.showMessageDialog(null,
"You have withdrawn: " + amount);
balance -= amount;
}
}
balanceLabel.setText(String.valueOf(balance));
}
}
您可能还想正确格式化数量,看看here。
此处的许多用户还认为您应该使用BigDecimal
而非double
进行财务计算。但由于这是一个简单的应用程序,double
会很好。