[英]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
,有多种方法:
FindSuspect
访问的另一个类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.