我正在创建一个简单的天气应用程序
以下是我问题的细节:-
我有一个主控制器(GeoWeatherMain.java)。当运行Appl时,这个类(GeoWeatherMain.class)将被加载,从而加载一个fxml文件。下面是它的代码:
Parent root = FXMLLoader.load(getClass().getResource("GeoWeatherMainUI.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();现在,GeoWeatherMainUI.fxml有了BorderPane对象实现。它由一个按钮(左窗格)组成,该按钮在中间窗格中单击加载另一个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是另一个处理不同按钮操作的控制器,events.Below是它的完整代码。
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的完整文档。不走运。在这里我也没有得到答案。请指点。
发布于 2012-10-03 15:36:50
如果LocName位于WeatherDetails.fxml中,那么LocName将为null是例外行为。因为@FXML Label LocName;是在GeoWeatherUIActionHandlers.java中定义的,它是GeoWeatherMainUI.fxml的一个控制器。将LocName从WeatherDetails移动到GeoWeatherMainUI FXML文件,并查看您仍然在哪里获取错误。
如果您的目标是设置WeatherDetails.fxml中标签的文本,那么请执行以下工作
- get the label by id (not fx:id) from centerPane with `((Label)centerPane.lookup("#myLabel")).setText("xyz")`, or
- get the controller of WeatherDetails and call getLocName().setText("xyz"). Assuming getter method exists in a controller class.
https://stackoverflow.com/questions/12694288
复制相似问题