我希望随时与FXML控制器类进行通信,以便从主应用程序或其他阶段更新屏幕上的信息。
这个可能吗?我没有找到任何方法实现它。
静态函数可能是一种方式,但它们无法访问表单的控件。
有什么想法吗?
这个可能吗?我没有找到任何方法实现它。
静态函数可能是一种方式,但它们无法访问表单的控件。
有什么想法吗?
您可以通过FXMLLoader
获取控制器
FXMLLoader fxmlLoader = new FXMLLoader();
Pane p = fxmlLoader.load(getClass().getResource("foo.fxml").openStream());
FooController fooController = (FooController) fxmlLoader.getController();
将其存储到您的主舞台中并提供getFooController()获取器方法。从其他类或阶段,每次需要刷新加载的“foo.fxml”页面时,请从其控制器请求:
getFooController().updatePage(strData);
updatePage() 可以像这样:
// ...
@FXML private Label lblData;
// ...
public void updatePage(String data){
lblData.setText(data);
}
// ...
在FooController类中。Label lblData
是什么和在哪里。FXMLLoader
得到了改进。对于JavaFX FXML应用程序,NetBeans将自动生成您的主类中的start方法,如下所示:
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
现在,我们只需要将FXMLLoader的load()
方法从静态实现更改为实例化实现,然后我们就可以使用实例的方法来获取控制器类,像这样:
//Static global variable for the controller (where MyController is the name of your controller class
static MyController myControllerHandle;
@Override
public void start(Stage stage) throws Exception {
//Set up instance instead of using static load() method
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = loader.load();
//Now we have access to getController() through the instance... don't forget the type cast
myControllerHandle = (MyController)loader.getController();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public class Controller implements javafx.fxml.Initializable {
@Override
public void initialize(URL location, ResourceBundle resources) {
// Implementing the Initializable interface means that this method
// will be called when the controller instance is created
App.setController(this);
}
}
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
}
@Override
public void start(Stage stage) throws Exception {
URL location = getClass().getResource("/sample.fxml");
FXMLLoader loader = createFXMLLoader(location);
Parent root = loader.load(location.openStream());
}
public FXMLLoader createFXMLLoader(URL location) {
return new FXMLLoader(location, null, new JavaFXBuilderFactory(), null, Charset.forName(FXMLLoader.DEFAULT_CHARSET_NAME));
}
Parent root = FXMLLoader.load(me.getClass().getResource("Form.fxml"));
Label lblData = (Label) root.lookup("#lblData");
if (lblData!=null) lblData.setText(strData);