javaFX加载异常和javaFX空指针异常

时间:2016-11-15 23:07:45

标签: java javafx nullpointerexception weather-api

我正在尝试启动一个小型的,快速制作的天气应用程序,我收到的错误是几个小时的谷歌搜索无法帮我解决。我见过类似的报道,但我面临的核心问题似乎是两位代码:

public void setTemperature() {
    getTemperatureField().setText(weather.getCurrentTemp() + "° F");
}

else {
        //didn't have a default image, so chose one at random
        getWeatherIcon().setImage(this.rainy);
    }

现在,我可以看到两位代码是相似的。两者都试图修改sample.fxml的元素,并且两者都在使用NPE失败。

我错过了什么?我的目标是能够将我从Weather.java类中的DarkSkies API中提取的信息用于设置 weatherIcon图像和温度文本,但这似乎不可能。

任何提示和帮助都会很棒,非常感谢一群男士和女士。

WeatherController.java

package sample;

import com.google.gson.Gson;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

public class WeatherController {

    public WeatherController() {
        weather = gson.fromJson(weather.getDarkSkyResponse(), Weather.class);
        setWeatherIcon();
        setTemperature();
    }

    //Instance variables for images
    Weather weather = new Weather();
    Gson gson = new Gson();

    @FXML private ImageView weatherIcon;
    @FXML private TextField temperatureField;
    Image sunny = new Image("images/sunny.png");
    Image rainy = new Image("images/rain.png");
    Image snowy = new Image("images/snow.png");
    Image cloudy = new Image("images/cloudy.png");
    Image partlyCloudy = new Image("images/partly_cloudy.png");
    Image chanceOfRain = new Image("images/chance_of_rain.png");
    Image chanceOfSnow = new Image("images/chance_of_snow.png");
    Image stormy = new Image("images/storm.png");
    Image thunderStorm = new Image("images/thunderstorm.png");

    public ImageView getWeatherIcon() {
        return this.weatherIcon;
    }

    public TextField getTemperatureField() {
        return this.temperatureField;
    }

    public void theButtonClick() {
        System.out.println("You clicked the button");
    } 

    public void setWeatherIcon() {
        String weatherType = (String)weather.getCurrentIcon();
        if (weatherType == "clear-day" || weatherType == "clear-night") {
            getWeatherIcon().setImage(this.sunny);
        }
        if (weatherType == "rain") {
            getWeatherIcon().setImage(this.rainy);
        }
        if (weatherType == "snow" || weatherType == "sleet") {
            getWeatherIcon().setImage(this.snowy);
        }
        if (weatherType == "cloudy") {
            getWeatherIcon().setImage(this.cloudy);
        }
        if (weatherType == "partly-cloudy-day") {
            getWeatherIcon().setImage(this.partlyCloudy);
        }
        else {
            //didn't have a default image, so chose one at random
            getWeatherIcon().setImage(this.rainy);
        }
    }

    public void setTemperature() {
        getTemperatureField().setText(weather.getCurrentTemp() + "° F");
    }

    public void printCurrentTemp() {
        System.out.println("Current temperature is: " + weather.getCurrentTemp() + "° F");
    }
}

Weather.java

package sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

public class Weather {

/* Instance Variables */
private double latitude;
private double longitude;
private String darkSkyURL = "https://api.darksky.net/forecast/[insert my key here]/";

/* Maps for each type of weather response */
private HashMap<String, Object> currently = new HashMap();
private HashMap<String, Object> minutely = new HashMap();
//private HashMap<String, Object> hourly = new HashMap();
//private HashMap<String, Object> daily = new HashMap();
//private HashMap<String, Object> alerts = new HashMap();

/* CONSTRUCTOR */
public Weather() {
    setLatitude(138.176374);
    setLongitude(-83.438066);
    setDarkSkyURL();
    populateFields();
}


/* SETTERS */
public void setLatitude(double lat) { this.latitude = lat; }
public void setLongitude(double lon) { this.longitude = lon; }
public void setDarkSkyURL() {
    darkSkyURL = getDarkSkyURL() + getLatitude() + "," + getLongitude();
}


/* GETTERS */
public double getLatitude() { return this.latitude; }
public double getLongitude() { return this.longitude; }
public String getDarkSkyURL() { return this.darkSkyURL; }

/* GETTERS FOR HASHMAP "CURRENTLY" */
public Object getCurrentTime() { return this.currently.get("time"); }
public Object getCurrentSummary() { return this.currently.get("summary"); }
public Object getCurrentIcon() { return this.currently.get("icon"); }
public Object getCurrentNearestStormDistance() { return this.currently.get("nearestStormDistance"); }
public Object getCurrentPrecipIntensity() { return this.currently.get("precipIntensity"); }
public Object getCurrentlyPrecipProbability() { return this.currently.get("precipProbability"); }
public Object getCurrentTemp() { return this.currently.get("temperature"); }
public Object getCurrentApparentTemp() { return this.currently.get("apparentTemperature"); }
public Object getCurrentDewPoint() { return this.currently.get("dewPoint"); }
public Object getCurrentHumidity() { return this.currently.get("humidity"); }
public Object getCurrentWindSpeed() { return this.currently.get("windSpeed"); }
public Object getCurrentWindBearing() { return this.currently.get("windBearing"); }
public Object getCurrentVisibility() { return this.currently.get("visibility"); }
public Object getCurrentCloudCover() { return this.currently.get("cloudCover"); }
public Object getCurrentPressure() { return this.currently.get("pressure"); }
public Object getCurrentOzone() { return this.currently.get("ozone"); }

/* GETTERS FOR HASHMAP MINUTELY */
public Object getMinutelySummary() { return this.minutely.get("summary"); }
public Object getMinutelyIcon() { return this.minutely.get("icon"); }
public Object getMinutelyTime() { return this.minutely.get("time"); }
public Object getMinutelyPrecipIntensity() { return this.minutely.get("precipIntensity"); }
public Object getMinutelyPrecipProbability() { return this.minutely.get("precipProbability"); }
public Object getMinutelyPrecipType() { return this.minutely.get("precipType"); }

/* DARK SKY FORECAST RETRIEVAL */
public String getDarkSkyResponse() {
    String fullResponse = "";
    try {
        URL darkSkyTarget = new URL(getDarkSkyURL());
        URLConnection dsConnection = darkSkyTarget.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(dsConnection.getInputStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            fullResponse += inputLine;
        in.close();
    } catch (MalformedURLException e) {
        System.out.println("new URL failed");
    } catch (IOException e) {
        System.out.println("openConnection failed");
    }

    return fullResponse;
}

private void populateFields() {
    populateCurrently();
    populateMinutely();

}

public void populateCurrently() {
    currently.put("time", 0);
    currently.put("summary", "");
    currently.put("icon", "");
    currently.put("nearestStormDistance", 0);
    currently.put("precipIntensity", 0.0);
    currently.put("precipProbability", 0);
    currently.put("precipType", "");
    currently.put("temperature", 0.0);
    currently.put("apparentTemperature", 0.0);
    currently.put("dewPoint", 0.0);
    currently.put("humidity", 0.0);
    currently.put("windSpeed", 0.0);
    currently.put("windBearing", 0);
    currently.put("visibility", 0.0);
    currently.put("cloudCover", 0.0);
    currently.put("pressure", 0.0);
    currently.put("ozone", 0.0);
}

public void populateMinutely() {
    minutely.put("summary", "");
    minutely.put("icon", "");
    minutely.put("time", 0);
    minutely.put("precipIntensity", 0.0);
    minutely.put("precipProbability", 0);
    minutely.put("precipType", "");
}

}

Main.java

package sample;

import com.google.gson.Gson;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception{

        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Weatherly");
        primaryStage.setScene(new Scene(root, 480, 800));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

sample.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?scenebuilder-background-color 0x99f3ffff?>

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="480.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="sample.WeatherController">
  <children>
    <BorderPane layoutX="0.0" layoutY="0.0" prefHeight="800.0" prefWidth="480.0">
      <bottom>
        <HBox prefHeight="133.0" prefWidth="480.0">
          <children>
            <Button fx:id="theButton" maxWidth="-1.0" mnemonicParsing="false" prefHeight="100.0" prefWidth="150.0" style="-fx-background-radius: 20px;&#10;&#10;" text="Button" textAlignment="CENTER">
              <HBox.margin>
                <Insets bottom="10.0" left="165.0" top="10.0" />
              </HBox.margin>
            </Button>
          </children>
        </HBox>
      </bottom>
      <center>
        <VBox prefHeight="-1.0" prefWidth="-1.0">
          <children>
            <TextField id="locationField" alignment="CENTER" editable="false" prefHeight="100.0" prefWidth="310.0" promptText="City, State" style="-fx-font-family: &quot;Verdana&quot;;&#10;-fx-font-size: 18px;&#10;-fx-font-weight: bold;&#10;&#10;&#10;" text="">
              <VBox.margin>
                <Insets bottom="10.0" top="120.0" />
              </VBox.margin>
            </TextField>
            <ImageView fx:id="weatherIcon" fitHeight="200.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" smooth="true" y="0.0">
              <image>
                <Image url="@../../images/sunny.png" />
              </image>
              <VBox.margin>
                <Insets bottom="10.0" left="55.0" right="55.0" top="10.0" />
              </VBox.margin>
            </ImageView>
            <TextField fx:id="temperatureField" alignment="CENTER" editable="false" maxWidth="-Infinity" minWidth="-Infinity" prefHeight="100.0" prefWidth="150.0" promptText="Temp" style="-fx-font-family: &quot;Tahoma&quot;;&#10;-fx-font-size: 24px;&#10;-fx-font-weight: bold;&#10;" text="">
              <VBox.margin>
                <Insets left="80.0" top="10.0" />
              </VBox.margin>
            </TextField>
          </children>
        </VBox>
      </center>
      <left>
        <Pane prefHeight="700.0" prefWidth="83.0" />
      </left>
      <right>
        <Pane prefHeight="700.0" prefWidth="87.0" />
      </right>
      <top>
        <MenuBar>
          <menus>
            <Menu mnemonicParsing="false" text="File">
              <items>
                <MenuItem mnemonicParsing="false" text="Close" />
              </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Edit">
              <items>
                <MenuItem mnemonicParsing="false" text="Delete" />
              </items>
            </Menu>
            <Menu mnemonicParsing="false" text="Help">
              <items>
                <MenuItem mnemonicParsing="false" text="About" />
              </items>
            </Menu>
          </menus>
        </MenuBar>
      </top>
    </BorderPane>
  </children>
</AnchorPane>

错误报告

    "C:\Program Files\Java\jdk1.8.0_73\bin\java" -Didea.launcher.port=7532 -Didea.launcher.bin.path=C:\Users\LibStaff\Desktop\IntelliJ\bin -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_73\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_73\jre\lib\rt.jar;E:\Computer Science\Java\Weatherly\out\production\Weatherly;C:\Users\LibStaff\Desktop\gson-master\gson\target\gson-2.7.1-SNAPSHOT.jar;C:\Users\LibStaff\Desktop\IntelliJ\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain sample.Main
    Exception in Application start method
    Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
        at java.lang.Thread.run(Thread.java:745)
        Caused by: javafx.fxml.LoadException: 
/E:/Computer%20Science/Java/Weatherly/out/production/Weatherly/sample/sample.fxml:13

        at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
        at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
        at sample.Main.start(Main.java:17)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
        at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
        at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
        at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more
Caused by: java.lang.NullPointerException
    at sample.WeatherController.setWeatherIcon(WeatherController.java:64)
    at sample.WeatherController.<init>(WeatherController.java:14)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at java.lang.Class.newInstance(Class.java:442)
    at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:51)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
    at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
    at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
    ... 17 more

0 个答案:

没有答案