我试图用Modell-View-Controller创建一个简单的扫雷游戏并且遇到了这个问题,这是我的View Class
public class View extends VBox implements Observer {
public Button [][] buttonarray;
public int width;
public int height;
public Model model ;
public TextArea textfeld;
public View(int buttoncolumn, int buttonrow, Model model){
this.model = model;
this.width = buttoncolumn;
this.height = buttonrow;
GridPane buttonpanel = new GridPane();
buttonpanel.setAlignment(Pos.CENTER);
Button [][] buttonarray = new Button [buttoncolumn][buttonrow];
textfeld = new TextArea();
textfeld.setMaxSize( buttoncolumn*25,60);
textfeld.setMinSize(buttoncolumn*25,60);
for(int x=0; x < buttoncolumn; x++) {
for (int y = 0; y < buttonrow; y++) {
buttonarray[x][y] = new Button();
buttonarray[x][y].setMinSize(25,25);
buttonarray[x][y].setMaxSize(25,25);
buttonpanel.add(buttonarray[x][y],x,y);
}
}
this.getChildren().add(buttonpanel);
this.getChildren().add(textfeld);
}
public Button [][] getButtonarray(){
return buttonarray;
}
public Button getButton(int x, int y){
return buttonarray[x][y];
}
public void update(Observable obs, Object o){
}
}
在Controller Class中,我试图实现这个
public class Controller implements Observer {
public Model model;
public View view;
public Controller(Model a, View b){
this.model = a;
this.view = b;
model.addObserver(this);
for (int x=0;x<model.width;x++){
for(int y=0;y<model.length;y++){
int xvalue = x;
int yvalue = y;
/* HERE IS THE PROBLEM */
view.getButtonarray()[x][y].setOnAction(event -> linksKlick(xvalue,yvalue));
}
}
model.addObserver(this);
}
事情发生了可怕的错误,有太多的例外情况,例如:
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at Uebung2.Controller.<init>(Controller.java:28)
at Uebung2.Main.start(Main.java:22)
我注意到,如果我用.setOnAction删除了一行,一切都会好的,但不是我想要的,有人可以关心解释原因吗?请注意,为了简短的问题,我删除了所有导入和不相关的方法