0
我想用JavaFx構建一個簡單的MVC應用程序。它取得左邊的TextField(tf1)的值,並在你按下按鈕b時將它複製到右邊的(tf2)中。所以,當我點擊Button b時定義要做什麼的時候,eclipse並不顯示錯誤,但是當我運行程序而不是返回按鈕時,會引發NullpointerException。JavaFx MVC Getter拋出空指針異常
你對我在做什麼錯了嗎?
在此先感謝!
Model.java:
package mvc;
public class Model {
private String firsttext;
private String lasttext;
public String getFirsttext() {
return firsttext;
}
public void setFirsttext(String firsttext) {
this.firsttext = firsttext;
}
public String getLasttext() {
return lasttext;
}
public void setLasttext(String lasttext) {
this.lasttext = lasttext;
}
}
View.java:
package mvc;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class View extends Application {
private TextField tf1;
private TextField tf2;
private Button b;
@Override
public void start(Stage stage) {
tf1 = new TextField();
tf2 = new TextField();
b = new Button("Copy");
FlowPane fp = new FlowPane();
fp.getChildren().addAll(tf1, b, tf2);
Scene scene = new Scene(fp, 600, 200);
stage.setScene(scene);
stage.show();
}
public void init(String args[]) {
launch(args);
}
public TextField getTf1() {
return tf1;
}
public void setTf1(TextField tf1) {
this.tf1 = tf1;
}
public TextField getTf2() {
return tf2;
}
public void setTf2(TextField tf2) {
this.tf2 = tf2;
}
public Button getB() {
return b;
}
public void setB(Button b) {
this.b = b;
}
}
Controller.java:
package mvc;
public class Controller {
private View view;
private Model model;
public Controller(View v, Model m) {
view = v;
model = m;
}
public void initController() {
view.getB().setOnAction(evt -> {
model.setFirsttext(view.getTf1().getText());
model.setLasttext(model.getFirsttext());
view.getTf2().setText(model.getLasttext());
});
}
}
App.java:
package mvc;
public class App {
public static void main(String[] args) {
Model m = new Model();
View v = new View();
Controller c = new Controller(v, m);
v.init(args);
c.initController();
}
}
普萊斯e在這裏追加一個stacktrace –
看看[這個問題](https://stackoverflow.com/questions/33303167/javafx-can-application-class-be-the-controller-class) - 它不完全相同,但答案解釋了「應用程序」類的預期用途。調用'launch'會創建一個新的實例,所以你看到的不是你傳遞給你的控制器的那個實例。最好使'App'類擴展應用程序,並且只從靜態上下文中調用'launch'。 – Itai
stacktrace是:線程「main」中的異常java.lang.NullPointerException \t at mvc.Controller.initController(Controller.java:14) \t at mvc.App.main(App.java:9) – ILikeC0ding