0
我想這個應用程序拋出一個錯誤,並顯示文本,但它只是繼續顯示空。該錯誤需要顯示該人是否試圖提取超過帳戶中的金額。這是我的。當餘額不夠高時,如何讓文本顯示出來?提前致謝!擺動顯示錯誤與擺動
林甚至不知道,如果需要處理,並在賬戶類,他們現在還是WithdrawListener顯示的錯誤...
MainFrame類
package appgui;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainFrame extends JFrame implements AccountDisplay {
private BankAccount account;
private JLabel label;
private JLabel errorLabel;
private JTextField amountField;
private static final int FRAME_HEIGHT = 600;
private static final int FRAME_WIDTH = 400;
public MainFrame(String t, BankAccount anAccount) {
super(t);
account = anAccount;
// Label that displays the result
label = new JLabel("Balance: " + account.getBalance());
label.setFont(new Font("Arial", Font.BOLD, 22));
label.setForeground(Color.RED);
errorLabel = new JLabel("Error: " + account.getErrors());
// Create the label, text field, and button for entering amount
JLabel amountLabel = new JLabel("Amount: ");
amountField = new JTextField(7);
// Create the Control Panel that holds all components
JPanel controlPanel = new JPanel();
controlPanel.add(amountLabel);
controlPanel.add(amountField);
controlPanel.add(createWithdrawButton());
controlPanel.add(createDepositeButton());
controlPanel.add(label);
controlPanel.add(errorLabel);
add(controlPanel);
setSize(FRAME_HEIGHT, FRAME_WIDTH);
//setLayout(new GridBagLayout());
}
private JButton createDepositeButton() {
JButton depositButton = new JButton("Deposit");
ActionListener depositLstener = new DepositListener(this);
depositButton.addActionListener(depositLstener);
return depositButton;
}
private JButton createWithdrawButton() {
JButton withdrawButton = new JButton("Withdraw");
ActionListener withdrawListener = new WithdrawListener(this);
withdrawButton.addActionListener(withdrawListener);
return withdrawButton;
}
public String getAmount() {
return this.amountField.getText();
}
public BankAccount getAccount() {
return this.account;
}
public JLabel getLabel() {
return this.label;
}
}
和賬戶類,我有檢查賬戶餘額
package appgui;
public class BankAccount {
private double balance;
private String error;
public BankAccount(int b) {
balance = b;
}
public void deposit(double amount) {
balance = balance + amount;
}
public void withdraw(double amount) {
if(balance - amount < 0) {
balance = balance;
setErrors("Can't withdraw that amount, account balance is too low.");
} else {
balance = balance - amount;
}
}
public double getBalance() {
return this.balance;
}
public String setErrors(String err) {
this.error = err;
return err;
}
public String getErrors() {
return this.error;
}
}
工作的席爾瓦謝謝你! – zachstarnes
不客氣:) –
您應該(通常)嘗試並避免將您的UI與您的數據/模型對象混合。一個更好的解決方案可能是拋出一個異常 – MadProgrammer