- [Java 기본]AWT, Listener, Event

Posted by 겨울에
2011. 5. 14. 16:14 scrap/ Java/JSP
출처 : http://cafe.naver.com/litave/383


//===========================================================================//
  본 내용은 2002년 제가 Java 강의를 수강하며 정리 했던 내용을
    기본으로 하여 정리하였습니다.
  - 마침 java 기초를 전파할 기회가 생겨 핑계김에 정리해 가려 합니다.
  작성자 : litwave
//---------------------------------------------------------------------------//

<목차>
1. Listener를 이용한 Event 실습
2. 익명 Inner 클래스를 이용한 Event 실습
3. 간단한 계산기 실습

//---------------------------------------------------------------------------//
// 수업중 소스
// Ex0121_01.java : Listener를 이용한 Event 처리 실습
 



import java.awt.*;
import java.awt.event.*;
class Ex0121_01_Sub extends Frame implements MouseListenerWindowListener {
    private List li = new List(5false);
    public Ex0121_01_Sub() {
        super("Ex0121_01");
        this.init();
        this.start();
        this.setSize(300200);
        this.setVisible(true);
    }
    public void init() {
        this.setLayout(new FlowLayout());
        for(char ch = 'A'; ch <= 'Z'; ch++) {
            li.add("" + ch + ch + ch);
        }
        this.add(li);
    }
    public void start() {
        this.addWindowListenerthis );
        li.addMouseListenerthis );
    }
    public void mouseClicked(MouseEvent e) {
        int x = e.getClickCount();
        if(x == 1) {
            String str = (String)li.getSelectedItem();
            System.out.println("선택된 내용 = " + str);
        }
    }
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
    public void windowClosed(WindowEvent e) {}
    public void windowOpened(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
}
public class Ex0121_01 {
    public static void main(String[] ar) {
        Ex0121_01_Sub es = new Ex0121_01_Sub();
    }
}

//---------------------------------------------------------------------------//
// Ex0121_02.java : 익명 Inner 클래스를 이용한 Event 실습




import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Ex0121_02_Sub extends Frame {
                                                //implements ActionListener{
    private Label lb = new Label("생년월일 : "Label.RIGHT);
    private Choice year = new Choice();
    private Choice month = new Choice();
    private Choice day = new Choice();
    private Label lb1 = new Label("년");
    private Label lb2 = new Label("월");
    private Label lb3 = new Label("일");
    private Button bt = new Button("확인");
    public Ex0121_02_Sub() {
        super("Ex0121_02");
        this.init();
        this.start();
        this.setSize(300200);
        this.setVisible(true);
    }

    public void init() {
        this.setLayout(new FlowLayout());
        this.add(lb);
        Calendar ca = Calendar.getInstance();
        int y = ca.get(Calendar.YEAR);
        for(int i = y; i >= 1900; i--) {
            year.add(String.valueOf(i));
        }
        this.add(year);
        this.add(lb1);
        for(int i = 1; i <= 12; i++) {
            month.add(String.valueOf(i));
        }
        this.add(month);
        this.add(lb2);
        for(int i = 1; i <= 31; i++) {
            day.add(String.valueOf(i));
        }
        this.add(day);
        this.add(lb3);
        this.add(bt);
    }

    public void start() {
        this.addWindowListenernew WindowAdapter() { 
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        bt.addActionListenernew ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String y = (String)year.getSelectedItem();
                String m = (String)month.getSelectedItem();
                String d = (String)day.getSelectedItem();
                System.out.println("생년월일 : " + y + "년 " + m + "월 " + d + "일");
            }
        });
    }
}
public class Ex0121_02 {
    public static void main(String[] ar) {
        Ex0121_02_Sub es = new Ex0121_02_Sub();
    }
}

//---------------------------------------------------------------------------//
// Ex0121_03.java : Action Event 실습


import java.awt.*;
import java.awt.event.*;
class Ex0121_03_Sub extends Frame
                implements ActionListener {
    private Button bt = new Button("확인");
    private Button bt1 = new Button("취소");
    public Ex0121_03_Sub() {
        super("Ex0121_03");
        this.init();
        this.start();
        this.setSize(300200);
        this.setVisible(true);
    }
    public void init() {
        this.setLayout(new FlowLayout());
        this.add(bt);
        this.add(bt1);
    }
    public void start() {
        bt.addActionListener(this);
        bt1.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e) {
        Button imsi = (Button)e.getSource();
        System.out.println(imsi.getLabel() + "을 누르셨습니다.");
        //if(imsi.getLabel().equals("확인")){
        //    System.out.println("확인을 눌렀다.");
        //}
        //else if(imsi.getLabel().equals("취소")){
        //    System.out.println("취소를 눌렀다.");
        //}
        /*
        if(e.getSource() == bt){
            System.out.println("확인을 눌렀다.");
        }
        else if(e.getSource() == bt1){
            System.out.println("취소를 눌렀다.");
        }
        */
    }
}
public class Ex0121_03 {
    public static void main(String[] ar) {
        Ex0121_03_Sub es = new Ex0121_03_Sub();
    }
}

//---------------------------------------------------------------------------//
// Ex0121_04.java : MouseEvent 실습



 
import java.awt.*;
import java.awt.event.*;
class Ex0121_04_Sub extends Frame
            implements MouseMotionListener{
    private Label lb = new Label("x = 000, y = 000");
    public Ex0121_04_Sub(){
        super("Ex0121_04");
        this.init();
        this.start();
        this.setSize(500400);
        this.setVisible(true);
    }
    public void init() {
        this.setLayout(new FlowLayout());
        lb.setFont(new Font("휴먼옛체"Font.BOLD20));
        this.add(lb);
    }
    public void start() {
        this.addMouseMotionListener(this);
    }
    public void mouseMoved(MouseEvent e) {
        if(e.getSource() == this){
            int x = e.getX();
            int y = e.getY();
            lb.setText("x = " + x + ", y = " + y);
        }
    }
    public void mouseDragged(MouseEvent e) {
        if(e.getSource() == this){
            int x = e.getX();
            int y = e.getY();
            lb.setText("x = " + x + ", y = " + y);
        }
    }
}
public class Ex0121_04 {
    public static void main(String[] ar) {
        Ex0121_04_Sub es = new Ex0121_04_Sub();
    }
}

//---------------------------------------------------------------------------//
// Ex0121_05.java : 계산기 실습


 

import java.awt.*;
import java.awt.event.*;
class Ex0121_05_Sub extends Frame
                    implements ActionListener {
    private Label lb = new Label("Su1 = "Label.RIGHT);
    private Label lb1 = new Label("Su2 = "Label.RIGHT);
    private Label lb2 = new Label("RES = "Label.RIGHT);
    private TextField su1 = new TextField();
    private TextField su2 = new TextField();
    private TextField result = new TextField();
    private Button add1 = new Button("+");
    private Button min1 = new Button("-");
    private Button mul1 = new Button("*");
    private Button div1 = new Button("/");
    private Button per1 = new Button("%");
    private Button end = new Button("종료");
    public Ex0121_05_Sub() {
        super("정수 계산기");
        this.init();
        this.start();
        this.setSize(250150);
        this.setVisible(true);
    }
    public void init() {
        this.setLayout(new GridLayout(51));
        Panel p = new Panel(new BorderLayout());
        p.add("West", lb);
        p.add("Center", su1);
        this.add(p);
        Panel p1 = new Panel(new BorderLayout());
        p1.add("West", lb1);
        p1.add("Center", su2);
        this.add(p1);
        Panel p2 = new Panel(new GridLayout(15));
        p2.add(add1);
        p2.add(min1);
        p2.add(mul1);
        p2.add(div1);
        p2.add(per1);
        this.add(p2);
        Panel p3 = new Panel(new BorderLayout());
        p3.add("West", lb2);
        p3.add("Center", result);
        this.add(p3);
        Panel p4 = new Panel(new FlowLayout(FlowLayout.RIGHT));
        p4.add(end);
        this.add(p4);
    }
    public void start() {
        add1.addActionListener(this);
        min1.addActionListener(this);
        mul1.addActionListener(this);
        div1.addActionListener(this);
        per1.addActionListener(this);
        add1.setActionCommand("yonsan");
        min1.setActionCommand("yonsan");
        mul1.setActionCommand("yonsan");
        div1.setActionCommand("yonsan");
        per1.setActionCommand("yonsan");
        end.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == end){
            System.exit(0);
        } else if(e.getActionCommand().equals("yonsan")) {
            int x = 0;
            try {
                x = Integer.parseInt(su1.getText().trim());
            } catch(NumberFormatException ee) {
                su1.setText("");
                su1.requestFocus();
                return;
            }
            int y = 0;
            try {
                y = Integer.parseInt(su2.getText().trim());
            } catch(NumberFormatException ee) {
                su2.setText("");
                su2.requestFocus();
                return;
            }
            char yon = ((Button)e.getSource()).getLabel().charAt(0);
            int tot = 0;
            switch(yon) {
            case '+': tot = x + ybreak;
            case '-': tot = x - ybreak;
            case '*': tot = x * ybreak;
            case '/': 
                try {
                    tot = x / y
                } catch(ArithmeticException ee) {
                    su2.setText("");
                    su2.requestFocus();
                    return;
                }
                break;
                case '%': 
                try {
                    tot = x % y
                } catch(ArithmeticException ee) {
                    su2.setText("");
                    su2.requestFocus();
                    return;
                }
                break;
            }
            result.setText(String.valueOf(tot));
        }
    }
}
public class Ex0121_05 {
    public static void main(String[] ar) {
        Ex0121_05_Sub es = new Ex0121_05_Sub();
    }
}

//---------------------------------------------------------------------------//
// 과제 : 아래와 같이 Window의 계산기와 동일한 모양을 AWT를 이용하여 구현하세요

// 기능은 다음 수업에서 진행

 



//===========================================================================//


/*
* 전일 과제를 통하여 구현한 화면을 기준으로 
* 수업 시간에 계산기 기능을 구현한 것입니다.
*/

import java.awt.*;
import java.awt.event.*;

class Ho0122_01_Sub extends Frame implements ActionListener {
    //메뉴바 정의
    private MenuBar mb = new MenuBar();
    private Menu medit = new Menu("편집(E)");
    private Menu mview = new Menu("보기(V)");
    private Menu mhelp = new Menu("도움말(H)");
    private MenuItem mcopy = new MenuItem("복사(C) Ctrl+C");
    private MenuItem mpaste = new MenuItem("붙여넣기(P) Ctrl+V");
    private CheckboxMenuItem mmt = new CheckboxMenuItem("일반용(T)");
    private CheckboxMenuItem mms = new CheckboxMenuItem("공학용(S)");
    private CheckboxMenuItem mmi = new CheckboxMenuItem("자릿수 구분 단위(I)");
    private MenuItem mhlist = new MenuItem("도움말 항목");
    private MenuItem minfo = new MenuItem("계산기 정보");

    //Frame Component 정의
    //Nor
    private Label view = new Label("0."Label.RIGHT);
    //Wst
    //Wst-Nor
    private Label mv = new Label("",Label.CENTER);
    //Wst-Cen
    //Wst-Cen-Grid(4,1)
    private Button mc = new Button("MC");
    private Button mr = new Button("MR");
    private Button ms = new Button("MS");
    private Button mp = new Button("M+");
    //Cen
    //Cen-Nor
    //Cen-Nor-Grid(1,3)
    private Button bs = new Button("Backspace");
    private Button ce = new Button("CE");
    private Button c = new Button("C");
    //Cen-Cen
    //Cen-Cen-Grid(4,5);
                            //숫자와 연산자는 배열로 처리
    private Button [] su = new Button[10];
    private String [] yonchar = new String[] {"/""*""-""+""="};
    private Button [] yon = new Button[5];

    private Button sqrt = new Button("sqrt");
    private Button na = new Button("%");
    private Button per = new Button("1/x");
    private Button sign = new Button("+/-");
    private Button jum = new Button(".");

    private boolean first = true;    // true : 처음 실행
    // false : 이미 한번 실행됨
    private double tot = 0.0;
    private char yonsan = '+';
    private boolean press = false;

    public double memory = 0.0;


    Ho0122_01_Sub(String str) {
        super(str);
        this.setSize(301233);
        this.setBackground(new Color(191191191));
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension di = tk.getScreenSize();
        Dimension di1 = this.getSize();
        setLocation((int)(di.getWidth()/2-di1.getWidth()/2), (int)(di.getHeight()/2-di1.getHeight()/2));
        setLayout(new BorderLayout(10,5));
        init();
        start();
        this.setResizable(false);
        this.setVisible(true);
    }
    public void init() {
        initMenu();
        initData();
        view.setBackground(new Color(255,255,255));
        view.setFont(new Font("휴먼옛체"Font.BOLD20));
        this.add("North", view);
        Panel p1 = new Panel(new BorderLayout(5,5));
        p1.setForeground(new Color(25500));
        p1.setFont(new Font("굴림"014));
        p1.add("North", mv);
        Panel p2 = new Panel(new GridLayout(4,1,5,5));
        p2.add(mc);
        p2.add(mr);
        p2.add(ms);
        p2.add(mp);
        p1.add("Center", p2);
        this.add("West", p1);
        Panel p3 = new Panel(new BorderLayout(5,5));
        Panel p4 = new Panel(new GridLayout(1,3,5,5));
        p4.setFont(new Font("굴림"013));
        p4.setForeground(new Color(25500));
        p4.add(bs);
        p4.add(ce);
        p4.add(c);
        p3.add("North", p4);
        Panel p5 = new Panel(new GridLayout(4,5,5,5));
        p5.setFont(new Font("굴림"012));
        p5.setForeground(new Color(0,0,255));
        
        for(int i=0; i < yon.length; i++) {
            yon[i].setForeground(new Color(25500));   
        }
        
        mv.setForeground(new Color(0,0,0));
        mv.setBackground(new Color(210,210,210));
        p5.add(su[7]);
        p5.add(su[8]);
        p5.add(su[9]);
        p5.add(yon[0]);
        p5.add(sqrt);
        p5.add(su[4]);
        p5.add(su[5]);
        p5.add(su[6]);
        p5.add(yon[1]);
        p5.add(na);
        p5.add(su[1]);
        p5.add(su[2]);
        p5.add(su[3]);
        p5.add(yon[2]);
        p5.add(per);
        p5.add(su[0]);
        p5.add(sign);
        p5.add(jum);
        p5.add(yon[3]);
        p5.add(yon[4]);
        p3.add("Center", p5);
        this.add("Center", p3);
    }
  
    public void initMenu() {
        this.setMenuBar(mb);
        mb.add(medit);
        medit.add(mcopy);
        medit.add(mpaste);
        mb.add(mview);
        mview.add(mmt);
        mview.add(mms);
        mview.addSeparator();
        mview.add(mmi);
        mb.add(mhelp);
        mhelp.add(mhlist);
        mhelp.addSeparator();
        mhelp.add(minfo);  
    }

    //데이타 초기화 Method
    public void initData() {
        for(int i=0; i < su.length; i++) {
            su[i] = new Button(String.valueOf(i));
        }
        for(int i=0; i < yon.length; i++) {
            yon[i] = new Button(yonchar[i]);
        }
    }

    public void start() {
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        for(int i = 0; i < su.length; i++) {
            su[i].addActionListenerthis );
            su[i].setActionCommand("su");   
            if(i < yon.length) {
                yon[i].addActionListenerthis );
                yon[i].setActionCommand("yon");
            }
        }

        sign.addActionListener(this);
        jum.addActionListener(this);

        ce.addActionListener(this);
        c.addActionListener(this);
        
        bs.addActionListener(this);
        
        mc.addActionListener(this);
        mr.addActionListener(this);
        ms.addActionListener(this);
        mp.addActionListener(this);

        sqrt.addActionListener(this);
        per.addActionListener(this);
        na.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("su")) {
            String imsi = ((Button)e.getSource()).getLabel().trim();        //e.getSource() 리턴값이 Object 타입이다.
            if(first == true) {
                //if(imsi != "0") first = false;
                view.setText(imsi + ".");
                if(imsi.equals("0")) {
                  return;
                }
                first = false;
            } else {
                if(press == true) {
                    String str = view.getText().trim();
                    str += imsi;
                    view.setText(str);
                } else {
                  String str = view.getText().trim();
                    str = str.substring(0, str.indexOf("."));
                    view.setText(str + imsi + ".");
                }
            }
        }
        else if(e.getActionCommand().equals("yon")) {
            double x = Double.parseDouble(view.getText());
            switch (yonsan) {
            case '+': tot += xbreak;
            case '-': tot -= xbreak;
            case '*': 
                        double imsi = tot;
                        int i = 1;
                        while(imsi-(int)imsi != 0) {
                            i *= 10;
                            imsi *= 10;
                        }
                        tot = (imsi * x/ i;
                        break;
            case '/': tot /= xbreak;
            }
            yonsan = ((Button)e.getSource()).getLabel().trim().charAt(0);
            first = true;
            press = false;
            double imsi = tot - (int)tot;
            if(imsi == 0.0) {
                view.setText((int)tot + ".");
            }
            else {
                view.setText(String.valueOf(tot));
                press = true;                         //과제.. 나눗셈 연산 후 Double 값이면, jum버튼 클릭한 것처럼 처리
            }
            if(yonsan == '=') {
                tot = 0.0;
                yonsan = '+';
            }
        }
        else if(e.getSource() == sign) {
            String str = view.getText().trim();
            if(str.equals("0.")) {
                return;
            }
            char imsi = str.charAt(0);
            if(imsi == '-') {
                str = str.substring(1);
            } else {
                str = "-" + str;
            }
            view.setText(str);
        }
        else if(e.getSource() == jum) {
            if(first == true) {
                view.setText("0.");
            }
            press = true;
            first = false;
        }
        else if(e.getSource() == ce) {
            first = true;
            press = false;
            view.setText("0.");
        }
        else if(e.getSource() == c) {
            first = true;
            press = false;
            view.setText("0.");
            tot = 0.0;
            yonsan = '+';
        }
        else if(e.getSource() == bs) {
            String str = view.getText().trim();
            if(str.length() == 3 && str.charAt(0== '-') {
                view.setText("0.");
                first = true;
                press = false;
                return;
            }
            if(str.length() == 2) {
                view.setText("0.");
                first = true;
                press = false;
                return;
            }
            if(press) {
                if(str.charAt(str.length()-1== '.') {
                    press = false;
                    return;
                }
                str = str.substring(0, str.length() - 1);
            } else {
                str = str.substring(0, str.length() - 2);
                str += ".";
            }
            view.setText(str);
        }
        else if(e.getSource() == mr) {
            double imsi = memory - (int)memory;
            if(imsi == 0.0) {
                view.setText((int)memory + ".");
                first = true;                    //memory에 0값이 있을 때 mr을 누른 후 숫자 입력시.. 0이 시작부분에 출력되는 것 막음
            } else {
                view.setText(String.valueOf(memory));
            }
        }
        else if(e.getSource() == mc) {
            memory = 0.0;
            mv.setText("");
        }
        else if(e.getSource() == ms) {
            String str = view.getText().trim();
            memory = Double.parseDouble(str);
            mv.setText("M");
        }
        else if(e.getSource() == mp) {
            String str = view.getText().trim();
            memory = Double.parseDouble(str);
            mv.setText("M");
        }
        else if(e.getSource() == sqrt) {
            double x = Double.parseDouble(view.getText());
            tot = Math.sqrt(x);
            double imsi = tot - (int)tot;
            if(imsi == 0.0) {
                view.setText((int)tot + ".");
                press = false;
                first = true;
                tot = 0.0;
            }
            else {
                view.setText(String.valueOf(tot));
                press = true;
                tot = 0.0;
            }
        }
        else if(e.getSource() == per) {
            double x = Double.parseDouble(view.getText());
            tot = 1 / x;
            double imsi = tot - (int)tot;
            if(imsi == 0.0) {
                view.setText((int)tot + ".");
                press = false;
                first = true;
                tot = 0.0;
            }
            else {
                view.setText(String.valueOf(tot));
                press = true;
                tot = 0.0;
            }
        }
        else if(e.getSource() == na) {
            double x = Double.parseDouble(view.getText());
            x = x / tot;
            double imsi = x - (int)x;
            if(imsi == 0.0) {
                view.setText((int)x + ".");
                press = false;
                first = true;
            }
            else {
                view.setText(String.valueOf(x));
                press = true;
            }
        }
    }
}

public class Ho0122_01 {
    public static void main(String [] ar) {
        Ho0122_01_Sub h1s = new Ho0122_01_Sub("계산기");
    }

}



--------------------------------------------------------------------------------------------------

>>>>>

Q. 2.0 - 1.1 하면 이상한 값이 나옵니당..

A. 
나누샘을 2진 부동 소수점 연산을 사용하는 double을 사용하기 때문에 오는 근본적인 문제임.. ㅋㅋ..
그래서 세밀한 연산에 대해서는 long 타입으로 변환 후 계산하고 결과를 돌려주던지... BigDecimal 클래스를 이용하라고 권고 되어 있는듯.. ㅋㅋ...
관련 링크 : http://blog.naver.com/redshoe?Redirect=Log&logNo=30021284413