EventHandler

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Button1Listener implements ActionListener { // (1) 독립적 이벤트 클래스

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
button.setText(“버튼 1이 눌려졌습니다”);
}

}

class MyFrame extends JFrame implements ActionListener { // (3) 인터페이스 구현
JButton b1;
JButton b2;
JButton b3;
JButton b4;
JButton b5;

private class Button2Listener implements ActionListener { // (2) 내부 이벤트 클래스

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == b2) {
b1.setText(“버튼2 이 눌려졌습니다”);
b2.setText(“버튼2 이 눌려졌습니다”);
b3.setText(“버튼2 이 눌려졌습니다”);
}
}

}

public MyFrame() {
setTitle(“Absolute Position Test”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);

JPanel p = new JPanel();
p.setLayout(null); // 절대위치크기 지정
b1 = new JButton(“Button #1”);
p.add(b1);
b2 = new JButton(“Button #2”);
p.add(b2);
b3 = new JButton(“Button #3”);
p.add(b3);
b4 = new JButton(“Button #4”);
p.add(b4);
b5 = new JButton(“Button #5”);
p.add(b5);
b1.setBounds(20, 5, 95, 30); // 절대위치크기 지정
b2.setBounds(55, 45, 105, 70); // 절대위치크기 지정
b3.setBounds(180, 15, 105, 90); // 절대위치크기 지정
b4.setBounds(80, 120, 105, 40); // 절대위치크기 지정
b5.setBounds(20, 170, 200, 30); // 절대위치크기 지정
add(p);

b1.addActionListener(new Button1Listener()); // (1) 독립적 이벤트 클래스 사용
b2.addActionListener(new Button2Listener()); // (2) 내부 이벤트 클래스 사용
b3.addActionListener(this);  // (3) 인터페이스 구현
b4.addActionListener(new ActionListener() { // (4) 무명 이벤트 클래스 사용
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == b4) {
b1.setText(“버튼4 이 눌려졌습니다”);
b2.setText(“버튼4 이 눌려졌습니다”);
b3.setText(“버튼4 이 눌려졌습니다”);
b4.setText(“버튼4 이 눌려졌습니다”);
}
}
});
b5.addActionListener(e -> { // (5) lambda 사용
b1.setText(“버튼5 이 눌려졌습니다”);
b2.setText(“버튼5 이 눌려졌습니다”);
b3.setText(“버튼5 이 눌려졌습니다”);
b4.setText(“버튼5 이 눌려졌습니다”);
b5.setText(“버튼5 이 눌려졌습니다”);
});

setVisible(true);
}

public void actionPerformed(ActionEvent e) { // (3) 인터페이스 구현

JButton button = (JButton) e.getSource();
if (button == b3) {
b1.setText(“버튼3 이 눌려졌습니다”);
b2.setText(“버튼3 이 눌려졌습니다”);
b3.setText(“버튼3 이 눌려졌습니다”);
}

}

}

public class AbsolutePositionTest {
public static void main(String args[]) {
MyFrame f = new MyFrame();
}
}

Equals & Contains

import java.util.*;

class Person implements Comparable<Person>
{
private static int count = 0;   // static (class) variables

protected String name;    // instance variables
protected int age;        // instance variables

public Person()
{
//System.out.println(“Person Constructor”); // this(“”, 0); error: call to this must be first statemenht in constructor
this(“”, 0);
}

public Person(String name, int age)
{
count++;
this.name = name;
this.age = age;
}

public Person(Person other)
{
this(other.name, other.age);
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge();
}
return false;
}

@Override
public int hashCode() {
return (41 * getName().hashCode() + getAge());
}

public boolean canEqual(Object other) {
return (other instanceof Person);
}

@Override
public String toString()                                        // Object.toString() overriding
{
return “Person Name: ” + name + ” Age: ” + age;
}

public void print()                                             // instance methods
{
System.out.println(“Person Name: ” + name + ” Age: ” + age);
}

public void set(String name, int age)
{
this.name = name;
this.age = age;
}

public void set(Person other)
{
this.name = other.name;
this.age = other.age;
}

public Person clone()
{
Person p = new Person(this.name, this.age);
return p;
}

public static void printCount()          // static (class) methods
{
System.out.println(“Person Count: ” + count);
}

public static int getCount() { return count; }                  // static (class) methods
public static void setCount(int value) { count = value; }                  // static (class) methods

public int compareTo(Person other)
    {
      String thisName = this.getName().toUpperCase();
      String otherName = ((Person)other).getName().toUpperCase();

      //ascending order
      return thisName.compareTo(otherName);
      //descending order
      //return otherName.compareTo(thisName);
    }

public static Comparator<Person> AgeComparator
                          = new Comparator<Person>() {

     public int compare(Person p1, Person p2) {

       int age1 = p1.getAge();
       int age2 = p2.getAge();

       //ascending order
       return age1 – age2;

       //descending order
       //return age2 – age1;
     }

};

}

///////////////////////////////////////////////////////////////////////////////////////

class Student extends Person
{
private static int count = 0;   // static (class) variables
protected int id;

public Student()
{
id = 5208;
}

public Student(String name, int age, int id)
{
super(name, age);
this.id = id;
count++;
}

public int getID()
{
return id;
}

public void setID(int id)
{
this.id = id;
}

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Student) {
Student that = (Student) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge() && this.getID() == that.getID();
}
return false;
}

@Override
public int hashCode() {
return (41 * super.hashCode() + getID());
}

public boolean canEqual(Object other) {
return (other instanceof Student);
}

@Override
public String toString() // Object.toString() overriding
{
return “Student Name: ” + name + ” Age: ” + age + ” ID: ” + id;
}

public void superPrint()
{
super.print();
}

public void print() // Person class print() method overriding
{
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” ID: ” + id);
}

public void set(String name, int age, int id)
{
super.set(name, age);
this.id = id;
}

public void set(String name, int age)
{
super.set(name, age);
}

public void set(Student other)
{
this.set(other.name, other.age, other.id);
}

public void set(Person other)
{
if (other instanceof Person)
super.set(other);
else
this.set((Student)other);
}

public Student clone()
{
Student s = new Student(this.name, this.age, this.id);
return s;
}

public static void printCount()         // static (class) methods
{
System.out.println(“Student Count: ” + count);
}

public static int getCount() { return count; }     // static (class) methods
public static void setCount(int value) { count = value; }       // static (class) methods

    public int compareTo(Student other)
    {
      String thisName = this.getName().toUpperCase();
      String otherName = ((Student)other).getName().toUpperCase();

      //ascending order
      return thisName.compareTo(otherName);
      //descending order
      //return otherName.compareTo(thisName);
    }

    public static Comparator<Student> AgeComparator
                          = new Comparator<Student>() {
     public int compare(Student p1, Student p2) {
       int age1 = p1.getAge();
       int age2 = p2.getAge();

       //ascending order
       return age1 – age2;

       //descending order
       //return age2 – age1;
     }

    };

    public static Comparator<Student> IDComparator
                          = new Comparator<Student>() {
     public int compare(Student p1, Student p2) {
       int id1 = p1.getID();
       int id2 = p2.getID();

       //ascending order
       return id1 – id2;

       //descending order
       //return id2 – id1;
     }

    };
}

class PersonStudentTest
{

public static void main(String[] args)
{

///////////////////////////////////////////////////////////////////////

Person jason1 = new Person(“Jason”, 10);
Person jason2 = new Person(“Jason”, 10);
Person jason3 = jason1;
Person jason4 = new Person(“Jason”, 20);

if (jason1 == jason2)
System.out.println(“jason1 == jason2”);
else
System.out.println(“jason1 != jason2”); //동일한 reference를 가리키지 않으므로 jason1 != jason2
if (jason1 == jason3)
System.out.println(“jason1 == jason3”); // 동일한 reference이므로 jason1 == jason3
else
System.out.println(“jason1 != jason3”);
if (jason1.equals(jason4))
System.out.println(“jason1 == jason4”);
else
System.out.println(“jason1 != jason4”); //동일한 reference를 가리키지 않으므로 jason1 != jason4

if (jason1.equals(jason2))
System.out.println(“jason1 equals to jason2”); // 내용이 같으므로  jason1 equals to jason2
else
System.out.println(“jason1 is not equal to jason2”);
if (jason1.equals(jason3))
System.out.println(“jason1 equals to jason3”); // 내용이 같으므로  jason1 equals to jason3
else
System.out.println(“jason1 is not equal to jason3”);
if (jason1.equals(jason4))
System.out.println(“jason1 equals jason4”);
else
System.out.println(“jason1 is not equal to jason4”); // 내용이 다르므로 jason1 is not equal to jason4

///////////////////////////////////////////////////////////////////////
Student john1 = new Student(“John”, 10, 100);
Student john2 = new Student(“John”, 10, 100);
Student john3 = john1;
Student john4 = new Student(“John”, 20, 100);
if (john1.equals(john2))
System.out.println(“john1 equals to john2”); // 내용이 같으므로  john1 equals to john2
else
System.out.println(“john1 is not equal to john2”);

if (john1.equals(john3))
System.out.println(“john1 equals to john3”); // 내용이 같으므로 jogn1 equals to john3
else
System.out.println(“john1 is not equal to john3”);

if (john1.equals(john4))
System.out.println(“john1 equals to john4”);
else
System.out.println(“john1 is not equal to john4”); // 내용이 다르므로 john1 is not equal to john4

Set<Student> sList5 = new HashSet<Student>();
sList5.add(john1);
        sList5.add(john2);
        sList5.add(john3);
        sList5.add(john4);
        sList5.forEach((s) -> System.out.println(s));
System.out.println(“sList5 contains john1 Student(\”John\”, 10, 100): ” + sList5.contains(john1));
System.out.println(“sList5 contains john2 Student(\”John\”, 10, 100): ” + sList5.contains(john2));
System.out.println(“sList5 contains john3 Student(\”John\”, 10, 100): ” + sList5.contains(john3));
System.out.println(“sList5 contains john4 Student(\”John\”, 20, 100):: ” + sList5.contains(john4));
System.out.println(“sList5 contains Student(\”John\”, 20, 100): ” + sList5.contains(new Student(“John”, 20, 100)));
System.out.println(“sList5 contains Student(\”John\”, 20, 200): ” + sList5.contains(new Student(“John”, 20, 200)));

Hashtable<Integer, Student> sList6 = new Hashtable<Integer, Student>();
sList6.put(1, john1);
        sList6.put(2, john2);
        sList6.put(3, john3);
        sList6.put(4, john4);
sList6.forEach((i, s) -> System.out.println(s));
System.out.println(“sList5 contains john1 Student(\”John\”, 10, 100): ” + sList5.contains(john1));
System.out.println(“sList5 contains john2 Student(\”John\”, 10, 100): ” + sList5.contains(john2));
System.out.println(“sList5 contains john3 Student(\”John\”, 10, 100): ” + sList5.contains(john3));
System.out.println(“sList5 contains john4 Student(\”John\”, 20, 100):: ” + sList5.contains(john4));
System.out.println(“sList5 contains Student(\”John\”, 20, 100): ” + sList5.contains(new Student(“John”, 20, 100)));
System.out.println(“sList5 contains Student(\”John\”, 20, 200): ” + sList5.contains(new Student(“John”, 20, 200)));

  }

}

Comparable & Comparator Interface

PersonStudentInterface

/////////////////////////////////

import java.util.*;

class Person implements Comparable<Person>
{
private static int count = 0;   // static (class) variables

protected String name;    // instance variables
protected int age;        // instance variables

public Person()
{
//System.out.println(“Person Constructor”); // this(“”, 0); error: call to this must be first statemenht in constructor
this(“”, 0);
}

public Person(String name, int age)
{
count++;
this.name = name;
this.age = age;
}

public Person(Person other)
{
this(other.name, other.age);
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge();
}
return false;
}

@Override
public int hashCode() {
return (41 * getName().hashCode() + getAge());
}

public boolean canEqual(Object other) {
return (other instanceof Person);
}

@Override
public String toString()                                        // Object.toString() overriding
{
return “Person Name: ” + name + ” Age: ” + age;
}

public void print()                                             // instance methods
{
System.out.println(“Person Name: ” + name + ” Age: ” + age);
}

public void set(String name, int age)
{
this.name = name;
this.age = age;
}

public void set(Person other)
{
this.name = other.name;
this.age = other.age;
}

public Person clone()
{
Person p = new Person(this.name, this.age);
return p;
}

public static void printCount()          // static (class) methods
{
System.out.println(“Person Count: ” + count);
}

public static int getCount() { return count; }                  // static (class) methods
public static void setCount(int value) { count = value; }                  // static (class) methods

public int compareTo(Person other)
    {
      String thisName = this.getName().toUpperCase();
      String otherName = ((Person)other).getName().toUpperCase();

      //ascending order
      return thisName.compareTo(otherName);
      //descending order
      //return otherName.compareTo(thisName);
    }

public static Comparator<Person> AgeComparator
                          = new Comparator<Person>() {

     public int compare(Person p1, Person p2) {

       int age1 = p1.getAge();
       int age2 = p2.getAge();

       //ascending order
       return age1 – age2;

       //descending order
       //return age2 – age1;
     }

};

}

///////////////////////////////////////////////////////////////////////////////////////

class Student extends Person
{
private static int count = 0;   // static (class) variables
protected int id;

public Student()
{
id = 5208;
}

public Student(String name, int age, int id)
{
super(name, age);
this.id = id;
count++;
}

public int getID()
{
return id;
}

public void setID(int id)
{
this.id = id;
}

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Student) {
Student that = (Student) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge() && this.getID() == that.getID();
}
return false;
}

@Override
public int hashCode() {
return (41 * super.hashCode() + getID());
}

public boolean canEqual(Object other) {
return (other instanceof Student);
}

@Override
public String toString() // Object.toString() overriding
{
return “Student Name: ” + name + ” Age: ” + age + ” ID: ” + id;
}

public void superPrint()
{
super.print();
}

public void print() // Person class print() method overriding
{
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” ID: ” + id);
}

public void set(String name, int age, int id)
{
super.set(name, age);
this.id = id;
}

public void set(String name, int age)
{
super.set(name, age);
}

public void set(Student other)
{
this.set(other.name, other.age, other.id);
}

public void set(Person other)
{
if (other instanceof Person)
super.set(other);
else
this.set((Student)other);
}

public Student clone()
{
Student s = new Student(this.name, this.age, this.id);
return s;
}

public static void printCount()         // static (class) methods
{
System.out.println(“Student Count: ” + count);
}

public static int getCount() { return count; }     // static (class) methods
public static void setCount(int value) { count = value; }       // static (class) methods

    public int compareTo(Student other)
    {
      String thisName = this.getName().toUpperCase();
      String otherName = ((Student)other).getName().toUpperCase();

      //ascending order
      return thisName.compareTo(otherName);
      //descending order
      //return otherName.compareTo(thisName);
    }

    public static Comparator<Student> AgeComparator
                          = new Comparator<Student>() {
     public int compare(Student p1, Student p2) {
       int age1 = p1.getAge();
       int age2 = p2.getAge();

       //ascending order
       return age1 – age2;

       //descending order
       //return age2 – age1;
     }

    };

    public static Comparator<Student> IDComparator
                          = new Comparator<Student>() {
     public int compare(Student p1, Student p2) {
       int id1 = p1.getID();
       int id2 = p2.getID();

       //ascending order
       return id1 – id2;

       //descending order
       //return id2 – id1;
     }

    };
}

 

class PersonStudentTest
{

public static void print(Object[] array) {
for(Object o : array) {
System.out.println(o);
}
}

public static void main(String[] args)
{

///////////////////////////////////////////////////////////////////////

Student[] sList = new Student[3];
sList[0] = new Student(“Kevin”, 0, 222);
sList[1] = new Student(“Jason”, 1, 333);
sList[2] = new Student(“John”, 2, 111);

System.out.println(“STUDENT SORT BY NAME (DEFAULT)!!!”);
Arrays.sort(sList);
print(sList);

System.out.println(“STUDENT SORT by AGE!!!”);
Arrays.sort(sList, Student.AgeComparator);
print(sList);

System.out.println(“STUDENT SORT by ID!!!”);
Arrays.sort(sList, Student.IDComparator);
print(sList);

///////////////////////////////////////////////////////////////////////
Student[] sList2 = new Student[3];
sList2[0] = new Student(“Kevin”, 0, 222);
sList2[1] = new Student(“Jason”, 1, 333);
sList2[2] = new Student(“John”, 2, 111);

System.out.println(“STUDENT SORT BY NAME (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
            public int compare(Student s1, Student s2) {
                return s1.getName().toUpperCase().compareTo(s2.getName().toUpperCase());
            }
        });
print(sList2);

System.out.println(“STUDENT SORT by AGE (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
            public int compare(Student s1, Student s2) {
                return s1.getAge() – s2.getAge();
            }
        });
print(sList2);

System.out.println(“STUDENT SORT by ID (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
            public int compare(Student s1, Student s2) {
                return s1.getID() – s2.getID();
            }
        });
print(sList2);

///////////////////////////////////////////////////////////////////////
Student[] sList3 = sList2;

System.out.println(“STUDENT SORT BY NAME (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
                ss1.getName().compareTo(ss2.getName())
        );
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

System.out.println(“STUDENT SORT by AGE (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
                Integer.compare(ss1.getAge(), ss2.getAge())
        );
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

System.out.println(“STUDENT SORT by ID (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
                Integer.compare(ss1.getID(), ss2.getID())
        );
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
List<Student> sList4 = new ArrayList<Student>();
sList4.add(new Student(“Kevin”, 0, 222));
        sList4.add(new Student(“Jason”, 1, 333));
        sList4.add(new Student(“John”, 2, 111));

System.out.println(“STUDENTLIST SORT BY NAME (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
                ss1.getName().compareTo(ss2.getName())
        );
sList4.forEach((s) -> System.out.println(s));

System.out.println(“STUDENTLIST SORT by AGE (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
                ss1.getAge() – ss2.getAge()
        );
sList4.forEach((s) -> System.out.println(s));

System.out.println(“STUDENTLIST SORT by ID (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
                ss1.getID() – ss2.getID()
        );
sList4.forEach((s) -> System.out.println(s));

}

}

BMICALCULATOR

표준체중계산기 (BMI Calculator)
-label, button, radiobutton, textfield

– 표준체중
// 남자표준체중 = 신장(m) x 신장(m) x 22
// 여자표준체중 = 신장(m) x 신장(m) x 21

– BMI
// BMI = 체중(kg)/신장^2(m^2)
// 20 미만 저체중 (Underweight)
// 20~24 정상 (Normal)
// 25~29 과체중 (Overweight)
// 30 이상 비만 (Obesity)

– 하루 권장 섭취량 
// 한국인 하루권장섭취량 남성 2600 kcal 여성 2100 kcal
// 기초대사량산출공식 (Herris Benedict Equation)
// 기초대사량(남성) = 66.47 + (13.75*weight) + (5*height) – (6.76*age)
// 기초대사량(여성) = 655.1 + (9.05*weight) + (1.85*height) – (4.68*age)
// 활동대사량 = 저활동적(1.3)/중간활동적(1.5)/활동적(1.75)
// 개인별 하루권장섭취량(kcal) = 기초대사량 * 활동대사량

 

enum BMI {
UNDERWEIGHT, NORMAL, OVERWEIGHT, OBESITY
}

enum Gender {
FEMALE, MALE
}

enum Activity {
LOW, MEDIUM, HIGH;

public static String[] names() {
String[] names = new String[Activity.values().length];
for (Activity t : Activity.values())
names[t.ordinal()] = t.toString();
return names;
}

public static Activity valueOf(int value)
{
switch(value) {
case 0:
return LOW;
case 1:
return MEDIUM;
case 2:
return HIGH;
default:
return null;
}
}
}

public class BMICalculator {

public int age = 20;
public double height = 165;
public double weight = 55;
public Gender gender = Gender.FEMALE;
public Activity activity = Activity.MEDIUM;

public BMICalculator()
{
this(20, 165.0, 55.0, Gender.FEMALE, Activity.MEDIUM);
}

public BMICalculator(int age, double height, double weight, Gender gender, Activity activity)
{
this.age = age;
this.height = height;
this.weight = weight;
this.gender = gender;
this.activity = activity;
}

public BMI calculateBMI()
{
double bmi = weight / (height * 0.01) / (height * 0.01);
if (bmi >= 0.0 && bmi < 20.0)
{
return BMI.UNDERWEIGHT;
}
else if (bmi >= 20.0 && bmi < 24.0)
{
return BMI.NORMAL;
}
else if (bmi >= 24.0 && bmi < 30.0)
{
return BMI.OVERWEIGHT;
}
else
{
return BMI.OBESITY;
}
}

public double calculateStandardWeight()
{
if (this.gender == Gender.MALE) {
return height * height * 22 * 0.0001;
}
return height * height * 21 * 0.0001;
}

// Herris Benedict Equation
public double calculateDailyCaloryIntake()
{
double activityCalory = 1.0;
switch (this.activity)
{
case LOW:
activityCalory = 1.3;
case MEDIUM:
activityCalory = 1.5;
case HIGH:
activityCalory = 1.75;
}

if (this.gender == Gender.MALE) {
return 66.47 + (13.75 * this.weight) + (5.0 * this.height) – (6.76 * (double)(this.age)) * activityCalory;
}
return 655.1 + (9.05 * this.weight) + (1.85 * this.height) – (4.68 * (double)(this.age)) * activityCalory;
}
}

/////////////////////////////////////////////////////////////////////////////

 

JLabel label1 = new JLabel(“나이”); // 레이블 초기화
JLabel label2 = new JLabel(“키(cm)”); // 레이블 초기화
JLabel label3 = new JLabel(“몸무게(kg)”); // 레이블 초기화
JLabel label4 = new JLabel(“성별”); // 레이블 초기화
JLabel label5 = new JLabel(“활동량”); // 레이블 초기화
JTextField textfield1 = new JTextField(10); // age 텍스트필드 초기화
JTextField textfield2 = new JTextField(10); // height 텍스트필드 초기화
JTextField textfield3 = new JTextField(10); // weight 텍스트필드 초기화
JRadioButton rbutton1 = new JRadioButton(“여자”, true); // gender 라디오버튼
JRadioButton rbutton2 = new JRadioButton(“남자”); // gender 라디오버튼
String[] names = {“Low”, “Medium”, “High”};
JComboBox<String> combobox1 = new JComboBox<String>(names); // acitivity 콤보박스

JButton button1 = new JButton(“계산”); // bmi calculator 버튼 초기화

JLabel label6 = new JLabel(“BMI 지수”); // 레이블 초기화
JLabel label7 = new JLabel(“정상 몸무게”); // 레이블 초기화
JLabel label8 = new JLabel(“일일 칼로리섭취량”); // 레이블 초기화
JTextField textfield4 = new JTextField(10); // bmi 텍스트필드 초기화
JTextField textfield5 = new JTextField(10); // standard weight 텍스트필드 초기화
JTextField textfield6 = new JTextField(10); // dailry calory intake 텍스트필드 초기화

JPanel panel = new JPanel(); // 패널 초기화
JPanel panel1 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel2 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel3 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel4 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel5 = new JPanel(); // 패널 초기화
JPanel panel6 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel7 = new JPanel(); // 패널 초기화
JPanel panel8 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel9 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel10 = new JPanel(new GridLayout(0, 2)); // 패널 초기화

 

public BMICalculatorFrame() {
super(“BMICalculatorFrame”);

// frame
panel1.add(label1);
panel1.add(textfield1);

panel2.add(label2);
panel2.add(textfield2);

panel3.add(label3);
panel3.add(textfield3);

panel5.add(rbutton1);
panel5.add(rbutton2);
panel4.add(label4);
panel4.add(panel5);

panel6.add(label5);
panel6.add(combobox1);

panel7.add(button1);

panel8.add(label6);
panel8.add(textfield4);

panel9.add(label7);
panel9.add(textfield5);

panel10.add(label8);
panel10.add(textfield6);

panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
panel.add(panel4);
panel.add(panel6);
panel.add(panel7);
panel.add(panel8);
panel.add(panel9);
panel.add(panel10);
add(panel);

// event
textfield1.addKeyListener(this);
textfield2.addKeyListener(this);
textfield3.addKeyListener(this);
button1.addActionListener(this);

setSize(350, 300);
setResizable(false);
setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

ARIDITY INDEX

건조지수(Aridity Index)를 구하고, 기후의 상태를 알려주는 프로그램을 작성한다

(1) 사용자에게 연강수량(Precipitation)과 연평균기온(Temperature)를 입력 받는다. 연강수량의 단위는 mm이고, 연평균기온의 단위는 oC이다.

(2) 건조지수를 다음 공식으로 계산하고 결과를 화면에 출력한다.
건조지수 De Martonne Aridity Index = Precipitation/ (Temperature + 10)

(3) 다음 기준에 따라 기후의 상태를 판단해서 화면에 출력한다.
AI >= 60 => Perhumid
30 <= AI < 60 => Humid
20 <= AI < 30 => SubHumid
15 <= AI < 20 => SemiArid
5 <= AI < 15 => Arid
AI < 5 => ExtremelyArid

 

///////////////////////////////////

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

//File: AridityIndexCalculator.java
//Class: AridityIndexCalculator
//Kyoung Shin Park (2016 Fall)

public class AridityIndexFrame extends JFrame implements ActionListener, KeyListener {

JLabel label1 = new JLabel(“연평균 온도 (C)”); // 레이블 초기화
JLabel label2 = new JLabel(“강수량 (mm)”); // 레이블 초기화
JLabel label3 = new JLabel(“건조지수 (LA)”); // 레이블 초기화

JTextField textfield1 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield2 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield3 = new JTextField(20); // 텍스트필드 초기화

JButton button1 = new JButton(“확인”); // 버튼 초기화

JPanel panel = new JPanel(); // 패널 초기화
JPanel panel1 = new JPanel(); // 패널 초기화
JPanel panel2 = new JPanel(); // 패널 초기화
JPanel panel3 = new JPanel(); // 패널 초기화

public AridityIndexFrame() {
super(“Aridity Index Frame”);

// frame
panel1.add(label1);
panel1.add(textfield1);

panel2.add(label2);
panel2.add(textfield2);

panel3.add(label3);
panel3.add(textfield3);

panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
panel.add(button1);
add(panel);

// event
textfield1.addKeyListener(this);
textfield2.addKeyListener(this);
button1.addActionListener(this);

setSize(350, 200);
setResizable(false);
setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private double ToDouble(String str)
{
return Double.parseDouble(str);
}

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == button1) {
this.dispose();
}
}

public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
Toolkit.getDefaultToolkit().beep();
System.out.println(“ENTER pressed”);
JTextField textfield = (JTextField) e.getSource();
double T = ToDouble(textfield1.getText());
double P = ToDouble(textfield2.getText());
textfield3.setText(“” + AridityIndexCalculator.Martonne(T, P));
}
}

public static void main(String[] args) {
new AridityIndexFrame();
}
}

GeometryType

import java.util.*;

public enum GeometryType {
NONE(0),
SPHERE(1),
CONE(2),
CYLINDER(3),
RECTANGULAR_PRISM(4),
SQUARE_PYRAMID(5),
ISOSCELES_TRIANGULAR_PRISM(6);

private int type;

private GeometryType(int type) {
this.type = type;
}

public int getType() {
return type;
}

public static GeometryType valueOf(int value) {
switch(value) {
case 1:
return SPHERE;
case 2:
return CONE;
case 3:
return CYLINDER;
case 4:
return RECTANGULAR_PRISM;
case 5:
return SQUARE_PYRAMID;
case 6:
return ISOSCELES_TRIANGULAR_PRISM;
default:
return null;
}
}

public static GeometryType nameOf(String name) {
if (name.contentEquals(“SPHERE”) || name.contentEquals(“Sphere”))
return SPHERE;
else if (name.contentEquals(“CONE”) || name.contentEquals(“Cone”))
return CONE;
else if (name.contentEquals(“CYLINDER”) || name.contentEquals(“Cylinder”))
return CYLINDER;
else if (name.contentEquals(“RECTANGULAR_PRISM”) || name.contentEquals(“RectangularPrism”))
return RECTANGULAR_PRISM;
else if (name.contentEquals(“SQUARE_PYRAMID”) || name.contentEquals(“SquarePyramid”))
return SQUARE_PYRAMID;
else if (name.contentEquals(“ISOSCELES_TRIANGULAR_PRISM”) || name.contentEquals(“IsoscelesTriangularPrism”))
return ISOSCELES_TRIANGULAR_PRISM;
else
return null;
}

public static String[] names() {
String[] names = new String[GeometryType.values().length];
for (GeometryType t : GeometryType.values())
names[t.ordinal()] = t.toString();
return names;
}
}

Midterm Extra 20%

Midterm Extra 20% (due by 11/16 23:59)

-중간고사 시험문제 프로그램(Point, Point3D, Bound, PolygonType, RegularPolygon, Utility)을 똑같이 작성하고 실행결과를 확인한다.

-이 프로그램을 직접 실행시켜서 중간고사 본인 답안과 비교 분석하는 보고서를 작성한다. (장수제한없음)

-중간고사 시험문제를 다시 푼다. (장수제한없음)

 

public class Point {
// 중간생략..
    public double[] get()
{
double[] xy = new double[2];
xy[0] = this.x;
xy[1] = this.y;
System.out.println(“get(): ” + “(” + xy[0] + “, ” + xy[1] + “)”);
return xy;
}
    public void set(double[] xy)
{
if (xy.length == 2) {
this.x = xy[0];
this.y = xy[1];
System.out.println(“set(xy[]): ” + this);
}
}
}
public class ArrayTest {
 public static void swap2(Point p, Point q)        // Java uses pass-by-value
{
  double[] t = p.get(); // T t = p
p.set(q.get());  // p = q
q.set(t);  // q = t
}
}

HW3

단국대학교 응용컴퓨터공학전공 JAVA프로그래밍1 (2016년 가을학기) 실습

날짜: 2016년 11월 10일

 

– 실습번호 : lab-03 (Due by 11/24)

– 실습제목 : GUI, swing, event

– 실습요약 : GUI 기반 입체 도형의 겉넓이(surface area)와 부피(volume) 구하기

– 준비자료 : HW2

 

11/24까지 online.dankook.ac.kr 이러닝으로 source code(*.java), binary code(*.class), 보고서(12-font 2~3 page)를 학번_이름_Ex3.zip으로 묶어서 이러닝에 제출한다. 보고서 (30%)

 

– 실습문제

  1. IGeometry 인터페이스와 Geometry 추상클래스는 아래와 같이 정의한다.

public interface IGeometry {

double getSurfaceArea(); // 겉넓이

double getVolume(); // 부피

}

public abstract class Geometry implements IGeometry {

public abstract GeometryType getType(); // 도형타입 (GeometryType)

}

 

  1. Geometry 추상클래스를 상속받은 Sphere, Cone, Cylinder, … 는 겉넓이(Surface Area), 부피(Volume)를 계산하여 출력한다.

 

  1. JFrame와 ItemListener와 KeyListener를 상속받은 GeometryFrame 클래스는 GUI를 정의하고 Geometry 계산을 구현한다.

-JComboBox, JLabel, JTextField, JButton, JPanel을 사용하여 GUI를 정의한다.

-Geometry 객체를 생성해서 텍스트필드에서 입력받은 값으로 SurfaceArea와 Volume을 계산하여 화면에 출력한다.

-public void itemStateChanged(ItemEvent e) { // 콤보박스 이벤트 내부구현 요망 }

-public void keyPressed(KeyEvent e) { // 키이벤트 관련 메소드 구현 요망 }