我试图在不同的FXML场景的控制器之间传递数据。但我无法将数据传递给另一个控制器。 这是我的第一个控制器。
public class FXMLDocumentController {
Session session;
private static Stage myStage;
@FXML
private Button button;
@FXML
private TextField txtAd;
@FXML
private TextField txtSifre;
@FXML
void handleButtonAction(ActionEvent event) {
session = NewHibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery("from Userss where ad = :code and sifre = :sifre");
query.setParameter("code", txtAd.getText().trim());
query.setParameter("sifre", txtSifre.getText().trim());
if (query.list().size() == 1) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Giriş");
alert.setHeaderText(null);
String s = "This is an example of JavaFX 8 Dialogs... ";
alert.setContentText(s);
alert.showAndWait();
}
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
} finally {
try {
session.close();
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDevam.fxml"));
DevamController devamController = loader.getController();
devamController.as("aaaaaaaaaaaaaaaaaaaaa");
AnchorPane login = (AnchorPane) loader.load();
Scene scene = new Scene(login);
myStage.setTitle("asd");
myStage.setScene(scene);
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
static void setStage(Stage stage) {
myStage = stage;
}
}
这是第二个控制器。
public class DevamController implements Initializable {
String as ;
@FXML
private Label lblAd;
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
lblAd.setText(as);
}
public void as (String a){
as = a;
}
}
我在这一行得到NullPointerException:
devamController.as("aaaaaaaaaaaaaaaaaaaaa");
我试过这个并且它不起作用: JavaFX: passing data between Controllers is always null
答案 0 :(得分:2)
控制器是从FXML文件加载的(因为它是定义的位置,带有fx:controller
),所以在用loader.load()
加载FXML之前它将为空。只需切换订单:
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDevam.fxml"));
AnchorPane login = (AnchorPane) loader.load();
DevamController devamController = loader.getController();
devamController.as("aaaaaaaaaaaaaaaaaaaaa");
您需要更新as()
方法中的标签,因为initialize()
已经执行过了。