[英]How to stop actionlistener from repeating previous actions
我對Java和編碼一般來說是新手。 我正在嘗試更新信息,但是每次更新不止一次時,它會重復以前的更新,例如,如果更新了帳戶3,之后又更新了帳戶4,則它通常會更新4,而空白會更新3。 如何使它僅更新我想要的內容?
updateBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuScreen.setVisible(false);
updateScreen.setVisible(true);
String id = JOptionPane.showInputDialog("Membership to update (1-4)");
if (id.equals("1")) {
tf_updateDOB.setText(account1.getAccountDOB());
tf_updatePlan.setText(account1.getAccountPlan());
tf_updateCard.setText(account1.getAccountCard());
tf_updateName.setText(account1.getAccountName());
updateSubmitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
account1.setAccountDOB(tf_updateDOB.getText());
account1.setAccountCard(tf_updateCard.getText());
account1.setAccountPlan(tf_updatePlan.getText());
account1.setAccountName(tf_updateName.getText());
menuScreen.setVisible(true);
updateScreen.setVisible(false);
}
});
} else if (id.equals("2")) {
tf_updateDOB.setText(account2.getAccountDOB());
tf_updatePlan.setText(account2.getAccountPlan());
tf_updateCard.setText(account2.getAccountCard());
tf_updateName.setText(account2.getAccountName());
updateSubmitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent f) {
account2.setAccountDOB(tf_updateDOB.getText());
account2.setAccountCard(tf_updateCard.getText());
account2.setAccountPlan(tf_updatePlan.getText());
account2.setAccountName(tf_updateName.getText());
menuScreen.setVisible(true);
updateScreen.setVisible(false);
}
});
}
歡迎來到SO。 我懷疑您的問題是您正在使用addActionListener
以便每次運行代碼時都添加另一個偵聽器。 單擊該按鈕時,您添加的所有以前的命令也將運行。
最好是增加一個偵聽器,以引用最后一個選擇的帳戶:
private class AccountUpdater implements ActionListener {
private Account account;
public void setAccount(Account account) {
this.account = account;
tf_updateDOB.setText(account.getAccountDOB());
tf_updatePlan.setText(account.getAccountPlan());
tf_updateCard.setText(account.getAccountCard());
tf_updateName.setText(account.getAccountName());
}
@Override
public void actionPerformed(ActionEvent f) {
account.setAccountDOB(tf_updateDOB.getText());
account.setAccountCard(tf_updateCard.getText());
account.setAccountPlan(tf_updatePlan.getText());
account.setAccountName(tf_updateName.getText());
menuScreen.setVisible(true);
updateScreen.setVisible(false);
}
}
AccountUpdater updater = new AccountUpdater();
updateSubmitBtn.addActionListener(updater);
然后,在選項對話框之后的代碼中,只需執行以下操作:
if (id.equals("1")) {
updater.setAccount(account1);
} else if (id.equals("2")) {
updater.setAccount(account2);
} ...
這也將使您的代碼更容易閱讀,重復次數更少。
如果帳戶中有一個id字段,那就更好了:
List<Account> accounts = ...;
accounts.stream()
.filter(ac -> ac.getId().equals(id))
.findAny().ifPresent(updater::setAccount);
然后,您就不需要if
, else if
語句(這通常是不良設計的標志)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.