반응형
package hello;
import javax.swing.*; // JFrame, JTextField, JLabel, JPanel, JButton 등 Swing 클래스들을 가져옴
import java.awt.*; // BorderLayout, GridLayout, FlowLayout, Color 등 AWT 클래스들을 가져옴
import java.util.ArrayList; // ArrayList 클래스를 가져옴
import javax.swing.border.EmptyBorder; // EmptyBorder 클래스를 가져옴
public class BMICalculator extends JFrame {
private JTextField nameField, heightField, weightField;
private JLabel resultLabel;
private ArrayList<Person> peopleList = new ArrayList<>(); // ArrayList to store Person objects
class Person {
private String name;
private double height; // in cm
private double weight; // in kg
public Person(String name, double height, double weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
public double calculateBMI() {
double heightInMeters = height / 100; // cm to meters
return weight / (heightInMeters * heightInMeters);
}
public String getBmiStatus() {
double bmi = calculateBMI();
if (bmi < 18.5) {
return "저체중";
} else if (bmi < 24.9) {
return "정상";
} else if (bmi < 29.9) {
return "과체중";
} else {
return "비만";
}
}
// 출력 메소드
@Override
public String toString() {
return "이름: " + name + ", 키: " + height + "cm, 몸무게: " + weight + "kg, BMI: "
+ String.format("%.2f", calculateBMI()) + " (" + getBmiStatus() + ")";
}
}
public BMICalculator() {
setTitle("BMI 계산기");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout(10, 10)); // 프레임과 패널 간 여백 설정
// 패널 생성
JPanel topPanel = new JPanel(new GridLayout(3, 2, 5, 5));
JPanel centerPanel = new JPanel(new FlowLayout());
JPanel bottomPanel = new JPanel(new FlowLayout());
// 패널 여백 설정
topPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
centerPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
bottomPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
// 패널 배경색 설정
topPanel.setBackground(Color.YELLOW);
centerPanel.setBackground(Color.GREEN);
bottomPanel.setBackground(Color.ORANGE);
// topPanel 구성
topPanel.add(new JLabel("이름:"));
nameField = new JTextField(10);
topPanel.add(nameField);
topPanel.add(new JLabel("키 (cm):"));
heightField = new JTextField(10);
topPanel.add(heightField);
topPanel.add(new JLabel("몸무게 (kg):"));
weightField = new JTextField(10);
topPanel.add(weightField);
// centerPanel 구성
resultLabel = new JLabel("여기에 BMI가 표시됩니다.");
centerPanel.add(resultLabel);
// bottomPanel 구성
JButton calculateButton = new JButton("BMI 계산");
JButton saveButton = new JButton("저장");
JButton listButton = new JButton("목록");
JButton exitButton = new JButton("종료");
// 종료 버튼에 람다식 이벤트 리스너 추가
exitButton.addActionListener(e -> System.exit(0)); // 프로그램 종료
// BMI 계산 버튼 이벤트 리스너 추가
calculateButton.addActionListener(e -> calculateBMI());
// 저장 버튼 이벤트 리스너 추가
saveButton.addActionListener(e -> savePerson());
// 목록 버튼 이벤트 리스너 추가
listButton.addActionListener(e -> displayPeopleList());
// 버튼 추가
bottomPanel.add(calculateButton);
bottomPanel.add(saveButton);
bottomPanel.add(listButton); // 목록 버튼 추가
bottomPanel.add(exitButton);
// 프레임에 패널 배치
add(topPanel, BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
// 컴포넌트 크기에 맞춰 프레임 크기 설정
pack();
// 프레임을 보이도록 설정
setVisible(true);
}
// BMI 계산 메서드
private void calculateBMI() {
try {
// 입력 값 가져오기
double height = Double.parseDouble(heightField.getText()) / 100; // cm 단위를 m로 변환
double weight = Double.parseDouble(weightField.getText());
// BMI 계산
double bmi = weight / (height * height);
String bmiStatus;
// BMI 상태 판별
if (bmi < 18.5) {
bmiStatus = "저체중";
} else if (bmi < 24.9) {
bmiStatus = "정상";
} else if (bmi < 29.9) {
bmiStatus = "과체중";
} else {
bmiStatus = "비만";
}
resultLabel.setText("BMI: " + String.format("%.2f", bmi) + " (" + bmiStatus + ")");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "키와 몸무게에 올바른 숫자를 입력하세요.", "입력 오류", JOptionPane.ERROR_MESSAGE);
}
}
// Person 객체 저장 메서드
private void savePerson() {
try {
// 입력 값 가져오기
String name = nameField.getText();
double height = Double.parseDouble(heightField.getText());
double weight = Double.parseDouble(weightField.getText());
// Person 객체 생성 및 ArrayList에 추가
Person person = new Person(name, height, weight);
peopleList.add(person);
// 저장된 정보 메시지 다이얼로그로 표시
JOptionPane.showMessageDialog(this, "저장된 정보:\n" + person, "저장 완료", JOptionPane.INFORMATION_MESSAGE);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "키와 몸무게에 올바른 숫자를 입력하세요.", "입력 오류", JOptionPane.ERROR_MESSAGE);
}
}
// peopleList 목록을 콘솔에 출력하는 메서드
private void displayPeopleList() {
if (peopleList.isEmpty()) {
System.out.println("저장된 정보가 없습니다.");
} else {
System.out.println("저장된 사람 목록:");
for (Person person : peopleList) {
System.out.println(person); // Person의 toString() 호출하여 출력
}
}
}
public static void main(String[] args) {
new BMICalculator();
}
}
반응형