首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >javafx -更新fxml对象中的值,该对象通过单击按钮动态加载。

问javafx -更新fxml对象中的值,该对象通过单击按钮动态加载。
EN

Stack Overflow用户
提问于 2012-10-02 16:21:48
回答 1查看 3.2K关注 0票数 2

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

以下是我问题的细节:-

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

代码语言:javascript
复制
Parent root = FXMLLoader.load(getClass().getResource("GeoWeatherMainUI.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();

现在,GeoWeatherMainUI.fxml有了BorderPane对象实现。它由一个按钮(左窗格)组成,该按钮在中间窗格中单击加载另一个fxml文件。GeoWeatherMainUI.fxml的骨架如下所示:

代码语言:javascript
复制
<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是它的完整代码。

代码语言:javascript
复制
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的完整文档。不走运。在这里我也没有得到答案。请指点。

EN

回答 1

Stack Overflow用户

发布于 2012-10-03 15:36:50

如果LocName位于WeatherDetails.fxml中,那么LocName将为null是例外行为。因为@FXML Label LocName;是在GeoWeatherUIActionHandlers.java中定义的,它是GeoWeatherMainUI.fxml的一个控制器。将LocName从WeatherDetails移动到GeoWeatherMainUI FXML文件,并查看您仍然在哪里获取错误。

如果您的目标是设置WeatherDetails.fxml中标签的文本,那么请执行以下工作

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

代码语言:javascript
复制
- 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.

​

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12694288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档