0% found this document useful (0 votes)
7 views9 pages

WeatherApp Assignment

The Weather Information App is a Java application that provides real-time weather updates using the OpenWeatherMap API, featuring a JavaFX GUI, unit conversion, error handling, and search history tracking. Key components include Main.java for GUI interaction, WeatherService.java for data fetching, and BackgroundChanger.java for dynamic backgrounds. Users can enter a city name to view weather details such as temperature, humidity, and wind speed, along with a history of their searches.

Uploaded by

mobsbouk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

WeatherApp Assignment

The Weather Information App is a Java application that provides real-time weather updates using the OpenWeatherMap API, featuring a JavaFX GUI, unit conversion, error handling, and search history tracking. Key components include Main.java for GUI interaction, WeatherService.java for data fetching, and BackgroundChanger.java for dynamic backgrounds. Users can enter a city name to view weather details such as temperature, humidity, and wind speed, along with a history of their searches.

Uploaded by

mobsbouk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Weather Information App - Java

Assignment
Overview
This Java application provides real-time weather updates using the OpenWeatherMap API.
It includes a GUI developed with JavaFX, supports unit conversion, error handling, search
history tracking, and dynamic backgrounds based on the time of day.

Features
• API integration with OpenWeatherMap

• JavaFX GUI with input, output, and control elements

• Temperature, humidity, wind speed, and condition display

• Weather icons and forecast display

• Temperature and wind speed unit conversion

• Error handling for network and user input issues

• History tracking with timestamps

• Dynamic background changes based on time of day

Source Code Overview

Main.java
Handles GUI, user interaction, and displays weather data.

WeatherService.java
Fetches and parses weather data from OpenWeatherMap API.

WeatherData.java
Model class to store weather data.

IconUtil.java
Utility to load weather icons from OpenWeatherMap.

BackgroundChanger.java
Changes GUI background based on time of day.
// WeatherApp - Main.java

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.*;

import javafx.scene.image.Image;

import javafx.scene.image.ImageView;

import javafx.scene.layout.*;

import javafx.stage.Stage;

import javafx.geometry.*;

import java.util.*;

public class Main extends Application {

private WeatherService weatherService = new WeatherService();

private Label temperatureLabel = new Label();

private Label humidityLabel = new Label();

private Label windSpeedLabel = new Label();

private Label conditionLabel = new Label();

private ImageView iconView = new ImageView();

private ListView<String> historyList = new ListView<>();

private ComboBox<String> unitBox = new ComboBox<>();

private BorderPane root = new BorderPane();

@Override

public void start(Stage primaryStage) {

TextField cityInput = new TextField();


cityInput.setPromptText("Enter city name");

Button searchButton = new Button("Search");

unitBox.getItems().addAll("Celsius", "Fahrenheit");

unitBox.setValue("Celsius");

HBox topBox = new HBox(10, cityInput, searchButton, unitBox);

topBox.setAlignment(Pos.CENTER);

topBox.setPadding(new Insets(10));

VBox weatherBox = new VBox(10, temperatureLabel, humidityLabel, windSpeedLabel,


conditionLabel, iconView);

weatherBox.setAlignment(Pos.CENTER);

root.setTop(topBox);

root.setCenter(weatherBox);

root.setRight(historyList);

searchButton.setOnAction(e -> {

String city = cityInput.getText().trim();

if (!city.isEmpty()) {

try {

WeatherData data = weatherService.getWeather(city, unitBox.getValue());

updateUI(data);

historyList.getItems().add(city + " @ " + new Date());

BackgroundChanger.updateBackground(root);

} catch (Exception ex) {


showAlert("Error", ex.getMessage());

} else {

showAlert("Input Error", "City name cannot be empty");

});

Scene scene = new Scene(root, 800, 600);

primaryStage.setTitle("Weather Information App");

primaryStage.setScene(scene);

primaryStage.show();

private void updateUI(WeatherData data) {

temperatureLabel.setText("Temperature: " + data.getTemperature() + " °" +


(unitBox.getValue().equals("Celsius") ? "C" : "F"));

humidityLabel.setText("Humidity: " + data.getHumidity() + "%");

windSpeedLabel.setText("Wind Speed: " + data.getWindSpeed() + " " +


(unitBox.getValue().equals("Celsius") ? "m/s" : "mph"));

conditionLabel.setText("Condition: " + data.getCondition());

iconView.setImage(IconUtil.getIcon(data.getIconCode()));

private void showAlert(String title, String content) {

Alert alert = new Alert(Alert.AlertType.ERROR);

alert.setTitle(title);

alert.setContentText(content);
alert.showAndWait();

public static void main(String[] args) {

launch(args);

// WeatherApp - WeatherService.java

import org.json.JSONObject;

import java.io.*;

import java.net.*;

public class WeatherService {

private static final String API_KEY = "YOUR_API_KEY"; // Replace with your


OpenWeatherMap API key

public WeatherData getWeather(String city, String unit) throws Exception {

String units = unit.equals("Celsius") ? "metric" : "imperial";

String urlString = "https://api.openweathermap.org/data/2.5/weather?q=" +


URLEncoder.encode(city, "UTF-8") +

"&appid=" + API_KEY + "&units=" + units;

URL url = new URL(urlString);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {

throw new RuntimeException("Failed to get weather data");

BufferedReader in = new BufferedReader(new


InputStreamReader(conn.getInputStream()));

String inputLine;

StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

in.close();

JSONObject json = new JSONObject(response.toString());

double temperature = json.getJSONObject("main").getDouble("temp");

int humidity = json.getJSONObject("main").getInt("humidity");

double windSpeed = json.getJSONObject("wind").getDouble("speed");

String condition = json.getJSONArray("weather").getJSONObject(0).getString("main");

String iconCode = json.getJSONArray("weather").getJSONObject(0).getString("icon");

return new WeatherData(temperature, humidity, windSpeed, condition, iconCode);

// WeatherApp - WeatherData.java
public class WeatherData {

private double temperature;

private int humidity;

private double windSpeed;

private String condition;

private String iconCode;

public WeatherData(double temperature, int humidity, double windSpeed, String


condition, String iconCode) {

this.temperature = temperature;

this.humidity = humidity;

this.windSpeed = windSpeed;

this.condition = condition;

this.iconCode = iconCode;

public double getTemperature() { return temperature; }

public int getHumidity() { return humidity; }

public double getWindSpeed() { return windSpeed; }

public String getCondition() { return condition; }

public String getIconCode() { return iconCode; }

// WeatherApp - IconUtil.java

import javafx.scene.image.Image;
public class IconUtil {

public static Image getIcon(String iconCode) {

return new Image("https://openweathermap.org/img/wn/" + iconCode + "@2x.png");

// WeatherApp - BackgroundChanger.java

import javafx.scene.layout.*;

import javafx.scene.image.Image;

import javafx.scene.image.ImageView;

import java.time.LocalTime;

public class BackgroundChanger {

public static void updateBackground(Pane pane) {

String bg;

int hour = LocalTime.now().getHour();

if (hour >= 6 && hour < 12) bg = "morning.jpg";

else if (hour >= 12 && hour < 18) bg = "afternoon.jpg";

else if (hour >= 18 && hour < 20) bg = "sunset.jpg";

else bg = "night.jpg";

BackgroundImage backgroundImage = new BackgroundImage(

new Image(BackgroundChanger.class.getResource("/backgrounds/" +
bg).toExternalForm()),
BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT,
BackgroundPosition.DEFAULT,

new BackgroundSize(100, 100, true, true, true, false));

pane.setBackground(new Background(backgroundImage));

Usage Instructions
1. Replace 'YOUR_API_KEY' in WeatherService.java with your actual OpenWeatherMap API
key.
2. Compile the project with Java 11 or higher.
3. Run Main.java to launch the application.
4. Enter a city name and select a unit to view the weather information.
5. Check the right-side panel for your search history.

Sample Output Screenshots

You might also like