javafx-更新按钮单击时动态加载的fxml对象中的值



我正在创建一个简单的天气应用程序

下面是我问题的细节:-

我有一个主控制器(GeoWeatherMain.java)。当Appl运行时,这个类(GeoWeather main.class)会被加载,它会加载一个fxml文件。以下是它的代码:-

Parent root = FXMLLoader.load(getClass().getResource("GeoWeatherMainUI.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();

现在,GeoWeatherMainUI.fxml实现了BorderPane对象。它由一个按钮(在左窗格上)组成,onclick在中央窗格中加载另一个fxml文件。GeoWeatherMainUI.fxml的框架如下所示:-

<BorderPane fx:id="MainBody" prefHeight="736.0" prefWidth="1140.0" xmlns:fx="http://javafx.com/fxml" fx:controller="geoweather.GeoWeatherUIActionHandlers">
.
.
<Button layoutX="91.0" layoutY="67.0" mnemonicParsing="false" onAction="#getCurrAndForecastWeatherCond" text="Get Weather Details" />
.
.
<BorderPane>

现在GeoWeatherUIActionHandlers.java是另一个处理不同按钮操作事件的控制器。下面是它的完整代码

public class GeoWeatherUIActionHandlers implements Initializable{
@FXML
BorderPane MainBody;
@FXML
Label LocName;/*LocName is fx id for a label*/
@FXML
private void getCurrAndForecastWeatherCond(ActionEvent event){
try{
Pane centerPane = FXMLLoader.load(getClass().getResource("WeatherDetails.fxml"));
MainBody.setCenter(centerPane);
/*LocName.setText("xyz");*/
}catch (IOException ex){
TextArea excep = new TextArea(ex.toString());
MainBody.setCenter(excep);
}catch(Exception e){
TextArea excep = new TextArea("Inside Exception : n" + e.toString());
MainBody.setCenter(excep);
}
}
@Override
public void initialize(URL url, ResourceBundle rb){}
}

现在,如果我想用新值更新加载的WeatherDetails.fxml文件,该怎么做?我按照上面注释的代码进行了尝试。(LocName.setText("xyz"))。但是,它不起作用(给出NullPointerException)。

我浏览了javafx@docs.oracle.com的完整文档。运气不好。我也没有得到答案。请引导。

如果LocName位于WeatherDetails.fxml内部,则LocName为null是一种例外行为。因为@FXML Label LocName;是在GeoWeatherUIActionHandlers.java中定义的,它是GeoWeatherMainUI.fxml的控制器。将LocName从WeatherDetails移到GeoWeatherMainUI fxml文件中,看看你在哪里仍然会收到错误。

如果你的目标是设置WeatherDetails.fxml内的标签文本,那么就进行

类似于当前GeoWeatherUIActionHandlers或的WeatherDetails控制器中的
  1. 在GeoWeatherUIActionHandlers中,在加载WeatherDetails.fxml 之后

    • 使用((Label)centerPane.lookup("#myLabel")).setText("xyz")从centerPane中按id(而非fx:id)获取标签,或者
    • 获取WeatherDetails的控制器并调用getLocName().setText("xyz")。假设getter方法存在于控制器类中

最新更新