Java 中 类 之间的事件处理

Event Handling between classes in Java

我有这个class:

public class Registry {
    private ArrayList<Communication> communicationList;
    private ArrayList<Suspect> suspectList;
}

主要 class,我添加了嫌疑人:

registry.addSuspect(s1);
registry.addSuspect(s2);
registry.addSuspect(s3);

我有一个 class 对应 window FindSuspect,它有一个文本字段和一个按钮。它将如何在 registry.suspectList 搜索嫌疑人的姓名? 这个 class 在 FindSuspect class:

里面
class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //There will be an if statement here, which will check if the textField.getText() is a suspect inside
            //the registry.suspectList
            JOptionPane.showMessageDialog(null,"Suspect " + textField.getText() + " not found!"); 
        }
    }

我很困惑,因为唯一的注册表项在我的主目录中,所以我无法从我的 FindSuspect class(buttonlistener 所在的位置)访问可疑列表,这意味着我不能寻找嫌疑人。

假设您的 Registry class 实例可以使用 actionPerformed 方法访问并且 Suspect class 有一个名为 name 的字段

您可以添加此代码

boolean matchNotFound = registry.getSuspectList()
        .stream()
        .filter(s -> s.getName().equals(textField.getText()))
        .noneMatch();

if (matchNotFound) {
    JOptionPane.showMessageDialog(null,"Suspect " + textField.getText() + " not found!");
}

要在 FindSuspect class 中访问 Registry 有多种方法:

  1. 在您的 Main class 中将其标记为静态并在此处访问它
  2. 将其作为“FindSuspect”构造函数中的参数传递
  3. 将它移动到另一个可以从 FindSuspect
  4. 访问的 class