본문 바로가기
Computer/Jlet

[15] 컴포넌트 - (5)ButtonComponent

by DogBull 2006. 8. 12.
버튼의 주된 목적은 무엇일까? 버튼이 눌렸는데도 아무런 일이 발생 하지 않는다면 아무런 소용이 없다. 버튼을 누르면 Event가 발생해야 한다. 여기서 Event가 발생한다는 것은 행위자의 행위가 전달루트를 통해서 어떤 일이 발생한다는 것이다. 해당 버튼을 setActionListener(전달루트)를 통해 등록한 후 버튼을 눌렀을 경우의 동작을 action메소드에서 정의하면 된다.

action은 인터페이스 ActionListener를 통해 오버라이딩 해야 한다.
잠시 인터페이스 ActionListener에 대해 알아 보자.

ActionListener 인터페이스의 클래스 선언부

public interface ActionListener
ActionListener 인터페이스의 추상 메소드
- public void action(Component c, Object obj)
  c : 액션이 발생한 컴포넌트
  obj : setActionListener 시에 넣은 Object 인수


이제 ButtonComponent에 대해 알아 보도록 하자.
ButtonComponent 클래스의 주요 생성자
- public ButtonComponent()
버튼을 생성한다.
- public ButtonComponent(String str, Image img)
지정된 문자열과 이미지로 버튼을 생성한다.
ButtonComponent 클래스의 주요 메소드
- public void setActionListener(ActionListener al, Object obj)
ActionListener를 등록 한다.
- public void setFont(Font f)
버튼의 폰트를 설정한다.
- public Font getFont()
버튼의 폰트를 가져온다.
- public boolean keyNotify(int type, int ch)
키 입력을 받으면 호출된다.
- public void setString(String str)
버튼의 문자열을 지정한다.
- public String getString()
버튼의 문자열을 돌려준다.
- public void setImage(Image img)
버튼의 이미지를 지정한다.
- public image getImage()
버튼의 이미지를 돌려준다.
- protected void layout()
하위 컴포넌트의 크기와 위치를 결정한다.



예제를 보도록 하자
import java.io.IOException;
import org.kwis.msp.lcdui.*;
import org.kwis.msp.lwc.*;

public class wipiTest extends Jlet implements ActionListener{
  Image img;

  ShellComponent   sc=    new ShellComponent();
  FormComponent    fc=    new FormComponent();
 
  LabelComponent   lb=    new LabelComponent();
  ButtonComponent  btn1;
  ButtonComponent  btn2;

  public void startApp(String args[]){
       try{
           img=    Image.createImage("p.gif");
           btn1=   new ButtonComponent(null, img);
          

           img=    Image.createImage("s.gif");
           btn2=   new ButtonComponent(null, img);

           btn1.setActionListener(this, null);
           btn2.setActionListener(this, null);

           fc.addComponent(lb);
           fc.addComponent(btn1);
           fc.addComponent(btn2);
           fc.setGab(10);

       }catch(IOException ie){}

       sc.addComponent(fc);
       sc.show();
  }

  public void destroyApp(boolean b){}

  public void action(Component c, Object obj){
       if(c==btn1){
           lb.setLabel("플레이어 시작");
       }else if(c==btn2){
           lb.setLabel("플레이어 멈춤");
       }
  }
};

출력 결과는 다음과 같다.