2013년 7월 4일 목요일

(130704) 9일차 EventTest4.java (Button 2개를 이용해서 각각 다른 이벤트 발생시키기)

 - 소스
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class EventTest4 extends JFrame implements ActionListener {

JTextArea ta;
JButton button1, button2;

public EventTest4() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// 컴포넌트 객체 생성
ta = new JTextArea();
button1 = new JButton("클릭");
button2 = new JButton("클릭");

// 버튼에 이벤트룰 부착
button1.addActionListener(this); // implements ActionListener - 내 클래스에서 받았으므로 this
button2.addActionListener(this);

// iframe에 부착
add(ta);
add("North", button1);
add("South", button2);

setTitle("Hello");
setSize(400, 300);
setVisible(true);
}

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

@Override // interface를 구현하였으므로 ActionListener의 actionPerformed 오버라이딩 필요
public void actionPerformed(ActionEvent e){
// 텍스트 에어리어에 데이터를 출력
// ta.setText("위쪽 버튼이 눌려졌네요"); // 버튼을 누르면 이벤트를 한번 적용
JButton b = (JButton)e.getSource();
if(b.equals(button1))
ta.append("위쪽 버튼이 눌려졌네요" + "\n"); // 버튼이 눌릴때마다 이벤트 적용
else if(b.equals(button2))
ta.append("아래쪽 버튼이 눌려졌네요" + "\n");


// String data = e.getActionCommand(); // 버튼의 라벨값을 리턴 (라벨의 이름으로 비교 가능)

/* // 이 방법으로도 가능
if((e.getSource()).equals(button1)) // e.getSource() 즉, Object로 비교
ta.append("위쪽 버튼이 눌려졌네요" + "\n");
else if((e.getSource()).equals(button2))
ta.append("아래쪽 버튼이 눌려졌네요" + "\n");
*/
}
}


 - 결과