0% found this document useful (0 votes)
10 views7 pages

Programming Assignment Unit 8-Submission1

The document details the Weather Information App, a JavaFX application that provides real-time weather updates using the OpenWeatherMap API. Users can enter a location to fetch and display weather details such as temperature, humidity, and conditions, along with a search history feature. Future enhancements include unit conversion, dynamic backgrounds, and a weather forecast feature.

Uploaded by

ws6028574
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)
10 views7 pages

Programming Assignment Unit 8-Submission1

The document details the Weather Information App, a JavaFX application that provides real-time weather updates using the OpenWeatherMap API. Users can enter a location to fetch and display weather details such as temperature, humidity, and conditions, along with a search history feature. Future enhancements include unit conversion, dynamic backgrounds, and a weather forecast feature.

Uploaded by

ws6028574
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/ 7

Waseem Saeed

University of the People


CS 1103-01 Programming 2 - AY2025-T2
Programming Assignment Unit 8
08/Jan/2025

A. WeatherApp.java Code Submission:


import javafx.application.Application;
import javafx.geometry.Insets;
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 java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONObject;

public class WeatherApp extends Application {

private TextField locationField;


private Label weatherInfoLabel;
private ImageView weatherIcon;
private TextArea historyArea;

private final String API_KEY = "da0ef9adc929d73816e404f839de72b7"; //


Replace with your API key
private final String API_URL =
"https://api.openweathermap.org/data/2.5/weather?q=%s&appid=" + API_KEY +
"&units=metric";

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Weather Information App");

// Input section
Label locationLabel = new Label("Enter Location:");
locationField = new TextField();
Button fetchButton = new Button("Get Weather");
fetchButton.setOnAction(e -> fetchWeatherData());

HBox inputSection = new HBox(10, locationLabel, locationField,


fetchButton);
inputSection.setPadding(new Insets(10));

// Weather information display section


weatherInfoLabel = new Label("Weather details will appear here.");
weatherIcon = new ImageView();
weatherIcon.setFitWidth(100);
weatherIcon.setPreserveRatio(true);

VBox weatherSection = new VBox(10, weatherIcon, weatherInfoLabel);


weatherSection.setPadding(new Insets(10));

// History section
Label historyLabel = new Label("Search History:");
historyArea = new TextArea();
historyArea.setEditable(false);

VBox historySection = new VBox(10, historyLabel, historyArea);


historySection.setPadding(new Insets(10));

// Layout
VBox root = new VBox(20, inputSection, weatherSection,
historySection);
root.setPadding(new Insets(10));

Scene scene = new Scene(root, 400, 500);


primaryStage.setScene(scene);
primaryStage.show();
}

private void fetchWeatherData() {


String location = locationField.getText().trim();

if (location.isEmpty()) {
weatherInfoLabel.setText("Please enter a location.");
return;
}

try {
String apiUrl = String.format(API_URL, location);
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
conn.connect();

int responseCode = conn.getResponseCode();


if (responseCode != 200) {
weatherInfoLabel.setText("Failed to fetch weather data.
Please try again.");
return;
}

Scanner scanner = new Scanner(url.openStream());


StringBuilder inline = new StringBuilder();
while (scanner.hasNext()) {
inline.append(scanner.nextLine());
}
scanner.close();

JSONObject data = new JSONObject(inline.toString());


updateWeatherUI(data);
} catch (IOException e) {
weatherInfoLabel.setText("Error fetching weather data.");
}
}
private void updateWeatherUI(JSONObject data) {
String location = data.getString("name");
JSONObject main = data.getJSONObject("main");
double temp = main.getDouble("temp");
double humidity = main.getDouble("humidity");

JSONObject weather = data.getJSONArray("weather").getJSONObject(0);


String description = weather.getString("description");
String iconCode = weather.getString("icon");

weatherInfoLabel.setText(String.format("Location: %s\nTemperature:
%.1f °C\nHumidity: %.1f%%\nCondition: %s",
location, temp, humidity, description));

String iconUrl = "https://openweathermap.org/img/wn/" + iconCode +


"@2x.png";
weatherIcon.setImage(new Image(iconUrl));

updateHistory(location, temp, description);


}

private void updateHistory(String location, double temp, String


description) {
String entry = String.format("%s - %.1f °C, %s\n", location, temp,
description);
historyArea.appendText(entry);
}

public static void main(String[] args) {


launch(args);
}
}
B. Screenshot of the Output:
C. Weather Information App - README
Introduction
The Weather Information App provides real-time weather updates for a specified location.
This application fetches data from the OpenWeatherMap API and displays weather details
such as temperature, humidity, and weather conditions. The app features a user-friendly
graphical interface built using JavaFX and allows users to search for weather information by
entering a location (city name).

How to Use the App


1. Launch the Application:
o Run the WeatherApp.java file to start the app. The main window will appear.
2. Enter a Location:
o Type the name of the city or location into the Location Text Field (for example,
"London").
3. Get Weather:
o Click the "Get Weather" button to fetch weather data for the entered location.
4. View Weather Information:
o The weather details will appear below, including:
 Location: The city name.
 Temperature: The current temperature in Celsius.
 Humidity: The current humidity level.
 Weather Condition: A brief description of the weather (e.g., sunny,
cloudy).
5. View Weather Icon:
o An icon representing the current weather condition will be displayed (e.g., a sun for
sunny weather).
6. Search History:
o Each time you search for a new location, the weather details will be added to the
Search History section with the timestamp, allowing you to view recent searches.
Technical Implementation
 API Integration:
o The app integrates with the OpenWeatherMap API to fetch real-time weather data
for the specified location. The weather information is retrieved in metric units
(Celsius for temperature).
 Graphical User Interface (GUI):
o The app is built using JavaFX and includes the following components:
 A TextField for entering the location (city name).
 A Button to trigger the weather data retrieval.
 A Label to display the weather details (temperature, humidity, and condition).
 An ImageView to display the corresponding weather icon.
 A TextArea to show the search history.
 Error Handling:
o The app handles invalid input by displaying a message when the location is empty or
the weather data cannot be fetched.
 Weather Icon Representation:
o The app uses weather condition icons provided by OpenWeatherMap to visually
represent the weather (e.g., clear sky, rain, clouds).

Example Walkthrough
Example Search:
 City Entered: London
 Weather Information:
o Location: London
o Temperature: 1.3 °C
o Humidity: 93%
o Condition: Overcast Clouds
Features & Enhancements
1. Unit Conversion:
o The current version of the app displays the temperature in Celsius. A future
enhancement could include an option to switch between Celsius and Fahrenheit.
2. Dynamic Background:
o The background could change based on the time of day (e.g., a sunset background in
the evening) to enhance the user experience.
3. Weather Forecast:
o A short-term weather forecast feature could be added, showing the weather for the
next few days.

Conclusion
This app demonstrates how to integrate a weather API, retrieve real-time data, and display it
in a clear, user-friendly format using JavaFX. With additional features like unit conversion,
dynamic backgrounds, and a weather forecast, the app can be further enhanced to provide a
more complete weather experience.

References
1. Oracle JavaFX Documentation
o This official Oracle documentation provides detailed information about using
JavaFX to build graphical user interfaces (GUIs) in Java.
o Link: JavaFX Documentation
2. OpenWeatherMap API Documentation
o The OpenWeatherMap API documentation offers all the necessary details on
how to access and use their API to retrieve weather data, along with examples
and guidelines for various API endpoints.
o Link: OpenWeatherMap API Documentation

You might also like