First version:
package helloworld;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.stage.Stage;
import org.w3c.dom.*;
/**
*
* @author Cristina
*/
public class HelloWorld extends Application {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
final WebEngine webEngine = new WebEngine("http://weather.yahooapis.com/forecastrss?w=868274&u=c");
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler
@Override
public void handle(ActionEvent event) {
NodeList meteo = webEngine.getDocument().getElementsByTagNameNS("http://xml.weather.yahoo.com/ns/rss/1.0", "condition");
System.out.println(meteo
.item(0)
.getAttributes()
.getNamedItem("temp")
.getNodeValue()
.toString());
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Fetching Weather Data From Yahoo");
Group root = new Group();
Scene scene = new Scene(root, 400, 100);
final WebEngine webEngine = new WebEngine("http://weather.yahooapis.com/forecastrss?w=868274&u=c");
Button btn = new Button();
btn.setText("Get temperature");
final Text temperatura = new Text(10,50,"Temperatura in Bucuresti");
btn.setOnAction(new EventHandler
@Override
public void handle(ActionEvent event) {
NodeList meteo = webEngine.getDocument().getElementsByTagNameNS("http://xml.weather.yahoo.com/ns/rss/1.0", "condition");
temperatura.setText("Hi! The temperature in Bucharest is: " + meteo
.item(0)
.getAttributes()
.getNamedItem("temp")
.getNodeValue()
.toString() + " degrees Celsius.");
}
});
root.getChildren().add(btn);
root.getChildren().add(temperatura);
primaryStage.setScene(scene);
primaryStage.show();
}
}
2 comments:
An interesting approach, but when I try the following line I get the annoying NullPointerException error, even when I use everything exactly the same way you have laid things out in this post:
NodeList meteo = webEngine.getDocument().getElementsByTagNameNS("http://xml.weather.yahoo.com/ns/rss/1.0", "condition");
Is the above line still valid under JavaFX 2.2, or have Yahoo changed things since you've written this post?
Hello and thanks for your comment!
I myself am a newbie as far as JavaFX and Web Services are concerned, but I've just run this application again and it still works for me as described in the post. It looks like Yahoo hasn't changed the way its weather service works and the program is still valid under the latest JavaFX version.
Post a Comment