본문 바로가기
Java

[Java] Java Swing으로 구현하는 날씨 기반 상태 변화 시뮬레이션

by teamnova 2024. 3. 21.

자바 스윙을 사용하여 간단한 날씨 기반 상태 변화 시뮬레이션 프로그램을 구현하는 방법을 알아보겠습니다. 이 프로그램은 날씨 상태(Sunny, Cloud, Rain)에 따라 사람(Person) 객체의 체력과 기분이 변화합니다. 날씨는 랜덤으로 변경되며, GUI에서는 날씨에 해당하는 이미지가 표시됩니다. 사람 객체의 상태 변화는 콘솔에 출력됩니다.

 

날씨가 맑다면 사람객체의 기분이 좋아지고, 체력이 10만큼 높아집니다.

구름낀 날씨라면 사람 객체의 기분은 그저 그렇고, 체력이 5만큼 높아집니다.

비가 오는 날시라면 사람 객체의 기분은 좋지 않고, 체력은 10만큼 줄어듭니다.

 

객체 지향 프로그래밍의 기본적인 개념과 자바 스윙의 사용법을 이해하는데 도움이 되었으면 좋겠습니다.

 

우선 시연영상부터 보겠습니다. 

 

 

다음은 전체 코드입니다. 

그 전에 날씨 변화 상태를 알려주기 위한 이미지는 다음과 같은 경로에 위치시켜줍니다.

 

 

전체코드입니다. 설명은 주석으로 적혀있으니 참고하시면 됩니다.

import javax.swing.*;
import java.awt.*;
import java.util.Random;

// Person 클래스: 사람 객체를 표현
class Person {
    private int health; // 체력
    private String mood; // 기분
    
    // 생성자: 기본 체력과 기분 설정
    public Person() {
        this.health = 50; // 기본 체력
        this.mood = "not bad"; // 기본 기분
    }
    
    // 날씨에 따른 상태 변경 메서드
    public synchronized void updateStatus(String weather) {
        if (weather.equals("Sunny")) {
            this.mood = "happy";
            this.health += 10; // 맑은 날씨는 체력과 기분을 개선
        } else if (weather.equals("Cloud")) {
            this.mood = "not bad";
            this.health += 5; // 흐린 날씨는 영향이 적음
        } else if (weather.equals("Rain")) {
            this.mood = "bad";
            this.health -= 10; // 비오는 날씨는 체력과 기분을 악화
        }
    }
    
    // 객체 상태를 문자열로 반환
    @Override
    public String toString() {
        return "Person State = Health: " + health + ", Mood: " + mood;
    }
}

// Weather 클래스: 날씨 상태 관리
class Weather {
    private String[] states = {"Sunny", "Cloud", "Rain"}; // 가능한 날씨 상태
    private Random random = new Random(); // 랜덤 객체 생성
    
    // 현재 날씨 상태를 랜덤하게 반환
    public String getCurrentWeather() {
        return states[random.nextInt(states.length)];
    }
}

// WeatherGUI 클래스: GUI 관리
class WeatherGUI extends JFrame {
    private JLabel weatherLabel; // 날씨 상태 표시 라벨
    private JLabel imageLabel; // 날씨 상태 이미지 표시 라벨
    private Weather weather;
    private Person person;
    
    public WeatherGUI(Weather weather, Person person) {
        this.weather = weather;
        this.person = person;
        
        setTitle("날씨 시뮬레이션");
        setSize(500, 500); // 창 크기 설정
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        
        weatherLabel = new JLabel("날씨: ");
        imageLabel = new JLabel(); // 이미지 라벨 초기화
        add(weatherLabel);
        add(imageLabel); // 이미지 라벨 추가
        
        // 날씨 업데이트 쓰레드: 날씨 상태를 변경하고 GUI 업데이트
        new Thread(() -> {
            while (true) {
                try {
                    String currentWeather = weather.getCurrentWeather();
                    person.updateStatus(currentWeather);
                    
                    // GUI 업데이트
                    SwingUtilities.invokeLater(() -> {
                        weatherLabel.setText("날씨: " + currentWeather);
                        updateImage(currentWeather); // 날씨에 따라 이미지 업데이트
                    });
                    
                    // 콘솔에 Person 상태 출력
                    System.out.println("Person's Status: " + person);
                    
                    Thread.sleep(10000); // 10초 대기
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    
    // 날씨에 따라 이미지를 업데이트하는 메서드
    private void updateImage(String weather) {
        ImageIcon imageIcon;
        switch (weather) {
            case "Sunny":
                imageIcon = new ImageIcon("image/sun.png");
                break;
            case "Cloud":
                imageIcon = new ImageIcon("image/cloud.png");
                break;
            case "Rain":
                imageIcon = new ImageIcon("image/rain.png");
                break;
            default:
                return; // 알 수 없는 날씨의 경우 아무것도 하지 않음
        }
        imageLabel.setIcon(imageIcon);
    }
}

// 메인 클래스: 프로그램 시작점
public class WeatherSimulation {
    public static void main(String[] args) {
        Weather weather = new Weather();
        Person person = new Person();
        
        // GUI 생성 및 표시
        SwingUtilities.invokeLater(() -> {
            WeatherGUI gui = new WeatherGUI(weather, person);
            gui.setVisible(true);
        });
    }
}