CS 1103 - Programming Assignment Unit 8
CS 1103 - Programming Assignment Unit 8
Program Code
AppLauncher.java
import javax.swing.*;
public class AppLauncher {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
new WeatherAppGui().setVisible(true);
}
});
}
}
WeatherApp.java
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
// retreive weather data from API - this backend logic will fetch the latest weather
// data from the external API and return it. The GUI will
// display this data to the user
public class WeatherApp {
// fetch weather data for given location
public static JSONObject getWeatherData(String locationName){
// get location coordinates using the geolocation API
JSONArray locationData = getLocationData(locationName);
"&hourly=temperature_2m,relativehumidity_2m,weathercode,windspeed_10m&timezone=America
%2FLos_Angeles";
try{
// call api and get response
HttpURLConnection conn = fetchApiResponse(urlString);
// close scanner
scanner.close();
// get temperature
JSONArray temperatureData = (JSONArray) hourly.get("temperature_2m");
double temperature = (double) temperatureData.get(index);
// get humidity
JSONArray relativeHumidity = (JSONArray) hourly.get("relativehumidity_2m");
long humidity = (long) relativeHumidity.get(index);
// get windspeed
JSONArray windspeedData = (JSONArray) hourly.get("windspeed_10m");
double windspeed = (double) windspeedData.get(index);
// build the weather json data object that we are going to access in our
frontend
JSONObject weatherData = new JSONObject();
weatherData.put("temperature", temperature);
weatherData.put("weather_condition", weatherCondition);
weatherData.put("humidity", humidity);
weatherData.put("windspeed", windspeed);
return weatherData;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
try{
// call api and get a response
HttpURLConnection conn = fetchApiResponse(urlString);
// read and store the resulting json data into our string builder
while(scanner.hasNext()){
resultJson.append(scanner.nextLine());
}
// close scanner
scanner.close();
// get the list of location data the API gtenerated from the lcoation
name
JSONArray locationData = (JSONArray) resultsJsonObj.get("results");
return locationData;
}
}catch(Exception e){
e.printStackTrace();
}
// iterate through the time list and see which one matches our current time
for(int i = 0; i < timeList.size(); i++){
String time = (String) timeList.get(i);
if(time.equalsIgnoreCase(currentTime)){
// return the index
return i;
}
}
return 0;
}
return formattedDateTime;
}
return weatherCondition;
}
}
WeatherAppGui.java
import org.json.simple.JSONObject;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public WeatherAppGui(){
// setup our gui and add a title
super("Weather App");
// configure gui to end the program's process once it has been closed
setDefaultCloseOperation(EXIT_ON_CLOSE);
// set the size of our gui (in pixels)
setSize(450, 650);
// make our layout manager null to manually position our components within the
gui
setLayout(null);
addGuiComponents();
}
add(searchTextField);
// weather image
JLabel weatherConditionImage = new JLabel(loadImage("src/assets/cloudy.png"));
weatherConditionImage.setBounds(0, 125, 450, 217);
add(weatherConditionImage);
// temperature text
JLabel temperatureText = new JLabel("10 C");
temperatureText.setBounds(0, 350, 450, 54);
temperatureText.setFont(new Font("Dialog", Font.BOLD, 48));
// humidity image
JLabel humidityImage = new JLabel(loadImage("src/assets/humidity.png"));
humidityImage.setBounds(15, 500, 74, 66);
add(humidityImage);
// humidity text
JLabel humidityText = new JLabel("<html><b>Humidity</b> 100%</html>");
humidityText.setBounds(90, 500, 85, 55);
humidityText.setFont(new Font("Dialog", Font.PLAIN, 16));
add(humidityText);
// windspeed image
JLabel windspeedImage = new JLabel(loadImage("src/assets/windspeed.png"));
windspeedImage.setBounds(220, 500, 74, 66);
add(windspeedImage);
// windspeed text
JLabel windspeedText = new JLabel("<html><b>Windspeed</b> 15km/h</html>");
windspeedText.setBounds(310, 500, 85, 55);
windspeedText.setFont(new Font("Dialog", Font.PLAIN, 16));
add(windspeedText);
// search button
JButton searchButton = new JButton(loadImage("src/assets/search.png"));
// change the cursor to a hand cursor when hovering over this button
searchButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
searchButton.setBounds(375, 13, 47, 45);
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// get location from user
String userInput = searchTextField.getText();
// update gui
weatherConditionImage.setIcon(loadImage("src/assets/clear.png"));
break;
case "Cloudy":
weatherConditionImage.setIcon(loadImage("src/assets/cloudy.png"));
break;
case "Rain":
weatherConditionImage.setIcon(loadImage("src/assets/rain.png"));
break;
case "Snow":
weatherConditionImage.setIcon(loadImage("src/assets/snow.pngImage"));
break;
}
Program Documentation
The Weather App is a Java-based application that provides users with real-time weather
information for a specified location. It fetches weather data from an external API and displays it
in a graphical user interface (GUI). Users can enter a location, and the app retrieves and
presents weather details, including temperature, weather condition, humidity, and wind speed.
This documentation outlines the project's architecture, technologies used, and the functionality
of each class within the application.
Technology used
The Weather App utilizes the following technologies and libraries:
- Java 18
- JSON Simple - Used to parse and read through JSON data
- HTTPURLConnection - Java's built-in library for making HTTP requests to fetch data
from external APIs.
File Summaries
AppLauncher.java
This file serves as the entry point for the Weather App. It initializes the GUI and displays the
main application window.
WeatherAppGui.java
This file represents the graphical user interface (GUI) of the Weather App. It is responsible for
displaying weather information for a specified location.
It also handles the layout and display of GUI components, including text fields, labels, buttons,
and images. It also implements the user interface for entering a location and updating the
weather information based on user input.
WeatherApp.java
The file contains the backend logic for fetching weather data from an external API. It retrieves
geographic coordinates for a location, fetches weather data for that location, and provides
methods to convert weather codes.
It encapsulates the core functionality of the Weather App. It includes methods to fetch weather
data and location coordinates, convert weather codes into readable weather conditions, and
manage API requests. It also acts as the bridge between the GUI and the external weather data
source, ensuring that weather information is retrieved and displayed accurately.