190426_Day15 복습, 이벤트 처리

복습

class Child
{
    Child()
    {
        My m = new My();
        m.goodChoice( this );
    }
    public void hello()
    {
        System.out.print("hi");
    }
    public static void main(String[] args)
    {
        Child c = new Child();
    }
}
Class My
{
    void goodChoice(Child c)
    {
        Child c = new Child();
        c.hello();
    }
}
  • <이벤트처리>

    • 사건이 발생했을 때 기능을 부여하는 것

    • 컴포넌트에서 사건(버튼, 스크롤바, 체크박스, 마우스 움직임) 발생시 기능 부여하는것

    • 이벤트 처리는 어떻게? 내가 기능부여할 컴포넌트 선정!

    class My
    {
        Frame f;
        Button bt_hello, bt_exit;
        Checkbox cb_apple;
    }
    • bt_hello, bt_exit list

    • 자료형은 Button, List 컴포넌트

    • API 문서 찾기 (각 클래스내에서 메소드 add Listener 찾기)

    • Button : addActionListener(ActionListener l)

    • List : addItemListener(ItemListener l)

    • 인터페이스 상속!!

    • 인터페이스 내의 선언된 메소드를 My클래스에서 구현(오버라이딩)

    • class My implements ActionListener, ItemListener
      {
        //implements 구현의 약속
        public void actionPerformed(ActionEvent e)
        {
      
        }
      }
    • -
package j0426;

import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class WindowCloseTest extends Frame implements WindowListener
{
    public WindowCloseTest()
    {
        setTitle("창닫기 테스트");
        setSize(300,300);
        setVisible(true);

        addWindowListener(this);
    }//생성자

    //우리는 얘만 필요해!
    public void windowClosing(WindowEvent e)
    {
        System.out.println( "X버튼 클릭" );
        //프로그램 종료 => System.exit(정수); 정수:0 양수[정상] 또는 음수[비정상종료]
//      System.exit(0);
    }

    public void windowOpened(WindowEvent e){}
    public void windowClosed(WindowEvent e){}
    public void windowIconified(WindowEvent e){}
    public void windowDeiconified(WindowEvent e){}
    public void windowActivated(WindowEvent e){}
    public void windowDeactivated(WindowEvent e){}

    public static void main(String[] args)
    {
        new WindowCloseTest();
    }
}
package j0426;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class WindowCloseTest2 extends WindowAdapter
{
    Frame f; // extends 저걸 했으니 Frame 이렇게 해줘야 함

    public WindowCloseTest2()
    {
        f = new Frame("창닫기 테스트2");
        f.setSize(300,500);
        f.setVisible(true);

        f.addWindowListener(this); // f : 이벤트소스, windowClosing() : 이벤트 핸들러
    }

    @Override
    public void windowClosing(WindowEvent e)
    {
        System.out.println("프레임 창 닫기");
        System.exit(0);
    }

    public static void main(String[] args)
    {
        new WindowCloseTest2();
    }
}
package com.encore.j0426;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import com.encore.j0425.ButtonEventTest;

//프레임창 우측상단의 X버튼 구현
public class WindowCloseTest3 extends Frame {


   public WindowCloseTest3() {
      setTitle("창닫기테스트3"); 

      setSize(300,300);
      setVisible(true);

      //My m = new My();
      //addWindowListener(m);//프레임과 밑에 추가된 핸들러를 연결!!

      //addWindowListener(new My());


      //익명의 내부클래스(Anonymous InnerClass)
      /*
       addWindowListener(             
               //extends WindowAdapter
                new WindowAdapter()
               {//클래스 시작

                    @Override
                    public void windowClosing(WindowEvent e) {
                      System.out.println("X버튼클릭(세번째)~!!");
                      System.exit(0);
                    }
                }//클래스 끝
        );
       */
       addWindowListener(new WindowAdapter() {//익명의 내부클래스 시작!!
           @Override
           public void windowClosing(WindowEvent e) {
             System.out.println("쉬었다 합시다~!!^^");  
             System.exit(0);
           }
       });

   }//생성자




   public static void main(String[] args) {
      new WindowCloseTest3();//프레임 객체 생성
   }

}
package j0426;


import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;


//프레임창 우측상단의 X버튼 구현
public class WindowCloseTest3 extends Frame {


   public WindowCloseTest3() {
      setTitle("창닫기테스트3"); 

      setSize(300,300);
      setVisible(true);

      //My m = new My();
      //addWindowListener(m);//프레임과 밑에 추가된 핸들러를 연결!!

      //addWindowListener(new My());


      //익명의 내부클래스(Anonymous InnerClass)
      /*
       addWindowListener(             
               //extends WindowAdapter
                new WindowAdapter()
               {//클래스 시작

                    @Override
                    public void windowClosing(WindowEvent e) {
                      System.out.println("X버튼클릭(세번째)~!!");
                      System.exit(0);
                    }
                }//클래스 끝
        );
       */
       addWindowListener(new WindowAdapter() {//익명의 내부클래스 시작!!
           @Override
           public void windowClosing(WindowEvent e) {
//           System.out.println("쉬었다 합시다~!!^^");  
//           System.exit(0);
              //현재 프레임의 타이틀을 '불타는 금요일'로 변경하시오
               setTitle("불타는 금요일");

           }
       });

   }//생성자




   public static void main(String[] args) {
      new WindowCloseTest3();//프레임 객체 생성
   }

}
package j0426;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//CardLayout테스트( 컴포넌트를 같은 위치에 부착)
public class CardTest implements ActionListener{
   Frame f;

   Panel redp, bluep, yellowp;//색깔패널
   Button bt1,bt2,bt3;//다음 버튼

   Panel card1,card2,card3;//카드

   CardLayout card;

   public CardTest() {
      f = new Frame("카드레이아웃");

      redp = new Panel();
       redp.setBackground(Color.RED);
      bluep = new Panel();
       bluep.setBackground(Color.BLUE);
      yellowp = new Panel();
       yellowp.setBackground(Color.YELLOW);

      bt1 = new Button("다음"); //301호
      bt2 = new Button("다음"); //302호
      bt3 = new Button("다음"); //303호

      card1 = new Panel();
        card1.setLayout(new BorderLayout(0, 10));
        card1.add("Center",redp);
        card1.add("South",bt1);

      card2 = new Panel();
        card2.setLayout(new BorderLayout(0, 10));
        card2.add("Center",bluep);
        card2.add("South",bt2);

      card3 = new Panel();
        card3.setLayout(new BorderLayout(0, 10));
        card3.add("Center",yellowp);
        card3.add("South",bt3);

      card =  new CardLayout();
      f.setLayout(card);
        f.add(card1,"first");//처음에 보이는 카드!!
        f.add(card2,"second");
        f.add(card3,"third");
      //f.add(붙일 컴포넌트, 별명);   alias별명

      //card.show (Container parent, String name);  
      // 를    보여라                 어디에                  무엇을(별명)
      card.show(f, "third");

      f.setSize(250,300);  
      f.setVisible(true);

      f.addWindowListener(new WindowAdapter() {
           @Override
           public void windowClosing(WindowEvent e) {
              System.exit(0);
           }
       });

      bt1.addActionListener(this);
      bt2.addActionListener(this);
      bt3.addActionListener(this);

   }//생성자

   @Override
   public void actionPerformed(ActionEvent e) {//이벤트 핸들러
      Object ob = e.getSource();//이벤트 소스의 주소(bt1 또는 bt2 또는 bt3의 주소)  
      //ob=301호 

      //첫번째버튼 눌렀을때 - 두번째 카드보이기
      if(ob == bt1) 
       card.show(f,"second");
      //두번째버튼 눌렀을때 - 세번째 카드보이기
      else if(ob == bt2)
       card.show(f,"third");
      //세번째버튼 눌렀을때 - 첫번째 카드보이기
      else //if(ob == bt3)
       card.show(f,"first");
   }
   public static void main(String[] args) {
       new CardTest();
   }

}
package j0426;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class HelloEventTest extends Frame implements ActionListener
{

    Button bt_hello, bt_clear, bt_exit;
    Checkbox cb1, cb2, cb3;
    TextField tf;
    Panel northp, centerp, southp;
    CheckboxGroup cg;

    public HelloEventTest()
    {
        setTitle("안녕이벤트");

        cg = new CheckboxGroup();
        bt_hello = new Button("안녕");
        bt_clear = new Button("지우기");
        bt_exit = new Button("종료");
        cb1 = new Checkbox("자바초급", cg, true );
        cb2 = new Checkbox("자바중급", cg, false );
        cb3 = new Checkbox("자바고급", cg, false );
        tf = new TextField(15);
        northp = new Panel();
        southp = new Panel();
        centerp = new Panel();


        northp.setLayout(new FlowLayout());
        northp.add(tf);
        northp.setBackground(Color.YELLOW);

        centerp.setLayout(new GridLayout(3, 1));
        centerp.add(cb1);
        centerp.add(cb2);
        centerp.add(cb3);

        southp.setLayout(new FlowLayout());
        southp.add(bt_hello);
        southp.add(bt_clear);
        southp.add(bt_exit);
        southp.setBackground(Color.RED);




        setLayout(new BorderLayout(3,1));
        add("North",northp);
        add("Center",centerp);
        add("South",southp);

        setSize(500,300);
        setVisible(true);


        eventUp();


    }//생성자

    private void eventUp()//이벤트 등록( 이벤트 소스의 수가 많을 때 )
    {
        //=======버튼=============
        bt_hello.addActionListener(this);
        bt_clear.addActionListener(this);
        bt_exit.addActionListener(this);

        //=======프레임============

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


    } //eventUp

    @Override
    public void actionPerformed(ActionEvent e)
    {   
        Object ob = e.getSource();

        //<데이터문자열> => String Label Text
        if(ob == bt_hello) {
            tf.setText("안녕");
        }else if(ob == bt_clear) {
            tf.setText("");
        }else {
        System.exit(0);
        }
    }

    public static void main(String[] args)
    {
        new HelloEventTest();   
    }
}
package com.encore.j0426;

import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class HelloEventTest extends Frame implements ActionListener{
  TextField tf;
  Checkbox cb1, cb2, cb3;
  Button bt_hello, bt_clear, bt_exit;

  Panel northp, centerp, southp;

  CheckboxGroup grade;

  public HelloEventTest() {
    setTitle("안녕이벤트");

    tf = new TextField(15);

    grade = new CheckboxGroup();


    cb1 = new Checkbox("자바초급",grade,true);
    cb2 = new Checkbox("자바중급",grade,false);
    cb3 = new Checkbox("자바고급",grade,false);

    bt_hello = new Button("안녕");
    bt_clear = new Button("지우기");
    bt_exit = new Button("종료");

    northp = new Panel();
    northp.setBackground(Color.YELLOW);
      northp.add(tf);

    centerp = new Panel();
    centerp.setLayout(new GridLayout(3,1));
      centerp.add(cb1);
      centerp.add(cb2);
      centerp.add(cb3);

    southp = new Panel();
    southp.setBackground(Color.PINK);
      southp.add(bt_hello);
      southp.add(bt_clear);
      southp.add(bt_exit);

    add("North",northp);
    add("Center",centerp);
    add("South",southp);

    setSize(300,300);
    setVisible(true);


    eventUp();
  }//생성자

  private void eventUp() {//이벤트 등록(이벤트 소스의 수가 많을 때)
      //============버튼==========================
      bt_hello.addActionListener(this);
      bt_clear.addActionListener(this);
      bt_exit.addActionListener(this);

      //============프레임==========================
      addWindowListener(new WindowAdapter() {
           @Override
           public void windowClosing(WindowEvent e) {
              System.exit(0);            
           }});
  }//eventUp

  @Override
  public void actionPerformed(ActionEvent e) {//이벤트 핸들러 (기능 추가)
     //System.out.println("action!!");
     Object ob = e.getSource();//이벤트를 발생시킨 소스의 참조변수(주소)를 얻어오기
     //ob= (bt_hello 또는 bt_clear 또는 bt_exit의 주소)


     //<데이터 문자열> ---> String, Label, Text

     //(메모리)주소비교  :  ==   !=
     if(ob==bt_hello) {//안녕 버튼클릭시
         //System.out.println("텍스트값:"+tf.getText());
        /* 
        if(cb1.getState()) //자바초급 Checkbox가 선택되었다면
         tf.setText("자바초급안녕~!!");
        else if(cb2.getState())
         tf.setText("자바중급안녕~!!");
        else //if(cb3.getState())
         tf.setText("자바고급안녕~!!");
        */
      Checkbox cb = grade.getSelectedCheckbox();//체크박스 그룹안에서 선택된 체크박스 얻어오기;  
        //cb = 선택에 따라  cb1, cb2, cb3
           tf.setText(cb.getLabel()+"안녕~!!!");
       /*
        if(cb==cb1) //자바초급 Checkbox가 선택되었다면
             tf.setText("자바초급안녕~!!");
        else if(cb==cb2)
             tf.setText("자바중급안녕~!!");
        else //if(cb==cb3)
             tf.setText("자바고급안녕~!!");
        */

     }else if(ob==bt_clear) {//지우기 버튼 클릭시
         //tf.setText(null);
         tf.setText("");

     }else {//if(ob==bt_exit)  종료 버튼 클릭시
         System.exit(0);
     }
  }//actionPerformed

  public static void main(String[] args) {
      new HelloEventTest();
  }
}
package j0426;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.Scrollbar;
import java.awt.TextArea;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//이벤트 소스: Scrollbar
// API  ----> addAdjustmentListener(AdjustmentListener l)

public class ColorChange extends Frame implements AdjustmentListener{
   Scrollbar sb_red, sb_blue, sb_green; 
   TextArea ta; 

   Panel bigp, p1,p2,p3;


   public ColorChange() {
     setTitle("색바꾸기");     

     //new Scrollbar(orientation, value, visible, minimum, maximum)
     sb_red = new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,265);
     sb_blue = new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,265);
     sb_green = new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,265);

     ta = new TextArea();
      ta.setBackground(Color.black);

     p1 = new Panel();
     p2 = new Panel();
     p3 = new Panel();

     bigp = new Panel();

     //속성지정
     p1.setLayout(new BorderLayout());
      p1.add("West",new Label("빨강"));
      p1.add("Center",sb_red);

     p2.setLayout(new BorderLayout());
      p2.add("West",new Label("파랑"));
      p2.add("Center",sb_blue);

     p3.setLayout(new BorderLayout());
      p3.add("West",new Label("초록"));
      p3.add("Center",sb_green);

     bigp.setLayout(new GridLayout(5,1,0,10));
      bigp.setBackground(Color.orange);
      bigp.add(new Label());
      bigp.add(p1);
      bigp.add(p2);
      bigp.add(p3);

     setLayout(new GridLayout());
      add(bigp);
      add(ta);

     setSize(600,300);
     setVisible(true);

     eventUp();
   }//생성자 

   private void eventUp() {//이벤트 소스 등록
      sb_red.addAdjustmentListener(this); 
      sb_blue.addAdjustmentListener(this); 
      sb_green.addAdjustmentListener(this); 

      addWindowListener(new WindowAdapter(){//익명의 내부클래스 
           public void windowClosing(WindowEvent e) {
               System.exit(0);}});

   }

   @Override
   public void adjustmentValueChanged(AdjustmentEvent e) {//이벤트 핸들러
      System.out.println("adjust!!");
      //기능 추가
      int r = sb_red.getValue(); //빨강 스크롤바의 조절바 위치값 얻어오기
      int b = sb_blue.getValue(); //파랑 스크롤바의 조절바 위치값 얻어오기
      int g = sb_green.getValue(); //초록 스크롤바의 조절바 위치값 얻어오기

      System.out.println("red="+ r+", green="+g+", blue="+b);
      /*
        <TextField tf에게  텍스트 주기>
           tf.setText("전달문자열");
        <TextAread ta에게  텍스트 주기>
           ta.setText("전달문자열"); - 이전텍스트 clear, 새로운 텍스트를 덮어쓰기
           ta.append("전달문자열");  - 이전텍스트에 이어쓰기
       */

      //ta.setText("red="+ r+", green="+g+", blue="+b);
      ta.append("red="+ r+", green="+g+", blue="+b+"\n");

      ta.setBackground(new Color(r,g,b));

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

}

+ Recent posts