我正在构建一个简单的应用程序,我在一个简单的MVC模式中实现它,控制器将事件处理程序添加到视图中。这是一个将处理程序附加到UI的控制器代码示例。
基本上,代码在单击UI的保存按钮时添加事件处理程序。 UI包含名称和ID号条目。我想要发生的是将名称和ID号传递给actionPerformed
函数。
ui.onAddStudent(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.print("test");
}
});
UI中的接收功能(在另一个文件中)如下。
public void onAddStudent(ActionListener handler){
//something missing here
addStudent.addActionListener(handler);
}
我不是真的喜欢Java,因为这不是我的强项。我实际上做JavaScript。现在,类似的处理程序在JavaScript中,可以使用call()
或apply()
方法调用处理程序和传递其他参数。如果上面的代码在JS中,那就像
//in the controller
ui.onAddStudent(function(event,id,name){
//I can use id and name
});
//in the UI
ui.onAddStudent = function(handler){
//store into a cache
//add handler to the button
}
//when student is added (button clicked)
handler.call(this,event,id,name);
我如何用Java做同样的事情?
答案 0 :(得分:3)
您有两种选择:
使用您自己的Event和Listener类型,其中包含此信息。例如:
public class StudentAddedEvent {
private long ID;
private String name;
...
}
public interface StudentAddedListener {
void studentAdded(StudentAddedEvent event);
}
UI将在按钮上注册一个ActionListener,此动作侦听器将执行:
@Override
public void actionPerformed(ActionEvent e) {
long id = getIdInGui();
String name = getNameInGui();
StudentAddedEvent event = new StudentAddedEvent(id, name);
for (StudentAddedListener listener : studentAddedListeners) {
listener.studentAdded(event);
}
}
答案 1 :(得分:1)
您也可以定义自己的Action
,并将它们设置为按钮(构造函数参数或setAction)和其他组件。
为此扩展AbstractAction。