2

シンプルな天気アプリケーションを作成しています

ここに私の質問の詳細があります:-

メインのコントローラー (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 オブジェクトが実装されています。これは、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 の完全なドキュメントを調べました。運がない。ここでも答えが得られませんでした。ガイドしてください。

4

1 に答える 1

1

LocName が WeatherDetails.fxml 内にある場合、LocName が null になることは例外的な動作です。@FXML Label LocName;GeoWeatherMainUI.fxml のコントローラである GeoWeatherUIActionHandlers.java で定義されているためです。LocName を WeatherDetails から GeoWeatherMainUI FXML ファイルに移動し、まだエラーが発生している場所かどうかを確認します。

WeatherDetails.fxml 内にあるラベルのテキストを設定することが目的の場合は、この作業を行います。

  1. 現在の GeoWeatherUIActionHandlers と同様の WeatherDetails のコントローラー、または

  2. GeoWeatherUIActionHandlers で、WeatherDetails.fxml をロードした後

    • ((Label)centerPane.lookup("#myLabel")).setText("xyz")、または
    • WeatherDetails のコントローラーを取得し、getLocName().setText("xyz") を呼び出します。コントローラークラスにゲッターメソッドが存在すると仮定します。
于 2012-10-03T15:36:50.197 に答える