我对 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
语句(这通常是糟糕设计的标志)。
关于java - 如何阻止 Action 监听器重复之前的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56231564/