Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Java programming unite 8

The Weather Information App is a Java application that provides real-time weather updates based on city names using a GUI built with Java Swing. It integrates with the OpenWeatherMap API to display current weather conditions, including temperature, humidity, and wind speed, with options to switch units. The app features error handling for invalid inputs and is designed for user-friendliness, requiring a valid API key and an internet connection to function.

Uploaded by

falakfraidoon
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java programming unite 8

The Weather Information App is a Java application that provides real-time weather updates based on city names using a GUI built with Java Swing. It integrates with the OpenWeatherMap API to display current weather conditions, including temperature, humidity, and wind speed, with options to switch units. The app features error handling for invalid inputs and is designed for user-friendliness, requiring a valid API key and an internet connection to function.

Uploaded by

falakfraidoon
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Java programming unite 8

The Weather Information App is a user-friendly Java application designed to


provide real-time weather updates based solely on city names. Utilizing a graphical
user interface (GUI) built with Java Swing, the app allows users to easily input
their desired city to retrieve current weather conditions. By integrating with a
weather API, OpenWeatherMap, the application fetches live weather data,
displaying essential details such as temperature, humidity, wind speed, and overall
weather conditions. To enhance user experience, the app offers the option to switch
between different units for temperature (Celsius and Fahrenheit) and wind speed
(meters per second and kilometers per hour). With built-in error handling, the
application effectively manages invalid city inputs and API request failures,
providing users with helpful feedback. Overall, the Weather Information App
serves as a practical and efficient tool for users to stay informed about the weather
in their chosen city.
Read me file:
Features
 Real-time weather updates based on city name input
 Displays temperature, humidity, wind speed, and weather conditions
 Option to switch between Celsius and Fahrenheit for temperature
 Option to switch between meters per second and kilometers per hour for
wind speed
 User-friendly graphical interface
How to Use
1. Run the application.
2. In the input field, type the name of the city for which you want to retrieve
weather information.
3. Click the "Get Weather" button.
4. View the displayed weather details, including temperature, humidity, wind
speed, and conditions.
Requirements
 Java Development Kit (JDK) installed on your machine
 An active internet connection to fetch weather data
 A valid API key from a weather service (e.g., OpenWeatherMap)
Setup
1. Clone the repository or download the source code.
2. Replace YOUR_API_KEY in the WeatherAppGUI.java file with your actual
API key.
3. Compile and run the application using an IDE or command line.

My API in the source code: 460a616923ee53bc6e7268a0324e9b08

Source code:
MainApp.java
import javax.swing.*;

public class MainApp {


public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
WeatherAppGUI weatherAppGUI = new WeatherAppGUI();
weatherAppGUI.setVisible(true);
});
}
}

WeatherAPI.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class WeatherAPI {


private String apiKey;

public WeatherAPI(String apiKey) {


this.apiKey = apiKey;
}

public WeatherData getWeather(String location) throws Exception {


String urlString =
"https://api.openweathermap.org/data/2.5/weather?q=" + location +
"&appid=" + apiKey + "&units=metric";
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: " +
conn.getResponseCode());
}

BufferedReader in = new BufferedReader(new


InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;

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


response.append(inputLine);
}
in.close();

// Print the raw response for debugging


System.out.println("API Response: " + response.toString());

return parseWeatherData(response.toString());
}

private WeatherData parseWeatherData(String response) {


WeatherData weatherData = new WeatherData();

try {
// Extract temperature
int tempIndex = response.indexOf("\"temp\":");
if (tempIndex != -1) {
String tempStr = response.substring(tempIndex + 7);
tempStr = tempStr.split(",")[0]; // Get the first value
after "temp"
weatherData.setTemperature(Double.parseDouble(tempStr));
}

// Extract humidity
int humidityIndex = response.indexOf("\"humidity\":");
if (humidityIndex != -1) {
String humidityStr = response.substring(humidityIndex +
11);
humidityStr = humidityStr.split(",")[0]; // Get the first
value after "humidity"
weatherData.setHumidity(Double.parseDouble(humidityStr));
}

// Extract wind speed


int windSpeedIndex = response.indexOf("\"speed\":");
if (windSpeedIndex != -1) {
String windSpeedStr = response.substring(windSpeedIndex +
8);
windSpeedStr = windSpeedStr.split(",")[0]; // Get the
first value after "speed"

weatherData.setWindSpeed(Double.parseDouble(windSpeedStr));
}

// Extract weather conditions


int conditionsIndex = response.indexOf("\"description\":");
if (conditionsIndex != -1) {
String conditionsStr = response.substring(conditionsIndex
+ 16);
conditionsStr = conditionsStr.split("\"")[0]; // Get the
first string after "description"
weatherData.setConditions(conditionsStr);
}
} catch (Exception e) {
e.printStackTrace();
}

return weatherData;
}
}
WeatherAppGUI.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

public class WeatherAppGUI extends JFrame {


private JTextField locationField;
private JTextArea weatherDisplay;
private WeatherAPI weatherAPI;
private JComboBox<String> unitComboBox;
private JTextArea historyDisplay;
private ArrayList<String> history;

public WeatherAppGUI() {
// Initialize the weather API with your API key
weatherAPI = new WeatherAPI("460a616923ee53bc6e7268a0324e9b08");
// Replace with your API key
history = new ArrayList<>();

// Set up the GUI


setTitle("Weather Information App");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Input panel
JPanel inputPanel = new JPanel();
locationField = new JTextField(15);
JButton searchButton = new JButton("Get Weather");
unitComboBox = new JComboBox<>(new String[]{"Celsius",
"Fahrenheit"});

inputPanel.add(new JLabel("Enter Location: "));


inputPanel.add(locationField);
inputPanel.add(searchButton);
inputPanel.add(unitComboBox);
add(inputPanel, BorderLayout.NORTH);

// Weather display area


weatherDisplay = new JTextArea();
weatherDisplay.setEditable(false);
add(new JScrollPane(weatherDisplay), BorderLayout.CENTER);
// History display area
historyDisplay = new JTextArea();
historyDisplay.setEditable(false);
historyDisplay.setPreferredSize(new Dimension(200, 100));
add(new JScrollPane(historyDisplay), BorderLayout.EAST);

// Action listener for the search button


searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String location = locationField.getText();
fetchWeather(location);
}
});
}

private void fetchWeather(String location) {


try {
WeatherData weatherData = weatherAPI.getWeather(location);
String unit = (String) unitComboBox.getSelectedItem();
double temperature = weatherData.getTemperature();

// Convert temperature to Fahrenheit if selected


if ("Fahrenheit".equals(unit)) {
temperature = (temperature * 9 / 5) + 32;
}

String weatherInfo = "Temperature: " + String.format("%.2f",


temperature) + "°" + (unit.equals("Celsius") ? "C" : "F") + "\n" +
"Humidity: " + weatherData.getHumidity()
+ "%\n" +
"Wind Speed: " +
weatherData.getWindSpeed() + " m/s\n" +
"Conditions: " +
weatherData.getConditions();
weatherDisplay.setText(weatherInfo);
updateBackground(weatherData.getConditions());
updateHistory(location);
} catch (Exception ex) {
weatherDisplay.setText("Error fetching weather data. Please
try again.");
}
}
private void updateBackground(String conditions) {
// Change background color based on weather conditions
switch (conditions.toLowerCase()) {
case "clear":
getContentPane().setBackground(Color.CYAN); // Clear sky
break;
case "clouds":
getContentPane().setBackground(Color.LIGHT_GRAY); //
Cloudy
break;
case "rain":
getContentPane().setBackground(Color.BLUE); // Rainy
break;
case "snow":
getContentPane().setBackground(Color.WHITE); // Snowy
break;
default:
getContentPane().setBackground(Color.WHITE); // Default
background
}
}

private void updateHistory(String location) {


history.add(location);
StringBuilder historyString = new StringBuilder("Search History:\
n");
for (String loc : history) {
historyString.append(loc).append("\n");
}
historyDisplay.setText(historyString.toString());
}
}

WeatherData.java
public class WeatherData {
private double temperature;
private double humidity;
private double windSpeed;
private String conditions;

// Getters and setters


public double getTemperature() {
return temperature;
}

public void setTemperature(double temperature) {


this.temperature = temperature;
}

public double getHumidity() {


return humidity;
}

public void setHumidity(double humidity) {


this.humidity = humidity;
}

public double getWindSpeed() {


return windSpeed;
}

public void setWindSpeed(double windSpeed) {


this.windSpeed = windSpeed;
}

public String getConditions() {


return conditions;
}

public void setConditions(String conditions) {


this.conditions = conditions;
}
}

Screenshot of the output:


References:
References:
Gaddis, T. (2019). Starting Out with Java: From Control Structures through Objects (6th ed.).
Pearson.
Eck, D. J. (2022). Introduction to programming using Java: Version 9, Swing
edition. Hobart and William Smith Colleges.
W3Schools. (n.d.). Java tutorial. W3Schools. https://www.w3schools.com/java/

You might also like