我在场景的窗格中有两个按钮。我添加了这样的事件处理程序:
Button reset=new Button ("Reset");
reset.addEventHandler(MouseEvent.MOUSE_CLICKED,new EventHandler<MouseEvent>(){
public void handle(MouseEvent event){
System.out.println("reseting");
model.reset();
Play(stage);
}});
Button guess=new Button ("Guess");
guess.addEventHandler(MouseEvent.MOUSE_CLICKED,new EventHandler<MouseEvent>(){
public void handle(MouseEvent event){
ArrayList<Integer> FullGuess=new ArrayList<Integer>();
boolean condition=true;
for (int y:fullGuess){
if (y==0){
condition=false;
}
}
}});
如何在另一个类中执行事件处理部分而不是像我一样直接在类中执行?
答案 0 :(得分:1)
您的片段使用anonymous class来处理事件,但您可以将匿名处理程序提升为封闭类的member或具有package-private访问权限的单独类。在任何一种情况下,您都希望将所需的List<Integer>
作为参数传递。
List<Integer> fullGuess = new ArrayList<Integer>();
…
Button guess = new Button("Guess");
guess.addEventHandler(MouseEvent.MOUSE_CLICKED, new MyEventHandler(fullGuess));
在另一个档案中:
class MyEventHandler implements EventHandler<MouseEvent> {
private final List<Integer> fullGuess;
public MyEventHandler(List<Integer> fullGuess) {
this.fullGuess = fullGuess;
}
@Override
public void handle(MouseEvent event) {
boolean condition = true;
for (int y : fullGuess) {
…
}
}
}