繁体   English   中英

Java中类之间的事件处理

[英]Event Handling between classes in Java

我有这门课:

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

在主课上,我添加了嫌疑人:

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

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

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 类(按钮侦听器所在的位置)访问嫌疑人列表,这意味着我无法搜索嫌疑人。

假设您的Registry类实例可以通过actionPerformed方法访问,并且Suspect类有一个名为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类中访问Registry ,有多种方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM