교재연습 문제 풀이 7-4
2009. 9. 1. 11:44
package net.jeongsam.gui; import java.awt.*; import java.awt.event.*; @SuppressWarnings("serial") public class EventEx03 extends Frame implements ActionListener { Button[] btnCity; Button btnExit; TextField txtMsg; Panel p1, p2; public EventEx03() { super("버튼/텍스트 필드 생성과 이벤트 처리"); String[] citys = {"천안", "당진", "속초", "서울", "제주"}; btnCity = new Button[citys.length]; for (int i = 0; i < citys.length; i++) { btnCity[i] = new Button(citys[i]); btnCity[i].addActionListener(this); } btnExit = new Button("종료"); btnExit.addActionListener(this); txtMsg = new TextField("선택한 지명: ", 12); p1 = new Panel(); p1.setLayout(new FlowLayout(FlowLayout.CENTER)); p1.add(new Label("당신이 좋아하는 지명을 선택하기 바랍니다. ")); for (Button b : btnCity) p1.add(b); p2 = new Panel(); p2.setLayout(new FlowLayout(FlowLayout.CENTER)); p2.add(txtMsg); p2.add(btnExit); add(p1, BorderLayout.NORTH); add(p2, BorderLayout.CENTER); setSize(600, 300); setVisible(true); } @Override public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() == btnExit) { dispose(); System.exit(0); } for (Button e : btnCity) { if (arg0.getSource() == e) { txtMsg.setText("선택한 지명: " + e.getLabel()); } } } /** * @param args */ public static void main(String[] args) { new EventEx03(); } }