141
9. 이이이 이이 이이이이이이이이 이이이이이이이 이이이이이 1

9. 이벤트 처리 그래픽프로그래밍

  • Upload
    moe

  • View
    79

  • Download
    0

Embed Size (px)

DESCRIPTION

9. 이벤트 처리 그래픽프로그래밍. 이벤트 처리. 이벤트 (Events). 이벤트 발생 버튼을 클릭할 때 텍스트필드에 문자를 타이핑할 때 콤보박스에서 아이템을 선택할 때 타이머가 타임아웃될 때 , 등등 ... 버튼 , 텍스트필드 등 GUI 콤포넌트 들이 이벤트 소스 (source) 임. 이벤트 (Events). 프로그래머는 많은 이벤트 중 관심 있는 이벤트에 대해서 만 필요한 반응을 보이도록 프로그램 작성 - PowerPoint PPT Presentation

Citation preview

Page 1: 9.  이벤트 처리 그래픽프로그래밍

9. 이벤트 처리

그래픽프로그래밍

자바프로그래밍 강원대학교 1

Page 2: 9.  이벤트 처리 그래픽프로그래밍

이벤트 처리

자바프로그래밍 강원대학교 2

Page 3: 9.  이벤트 처리 그래픽프로그래밍

이벤트 (Events)

• 이벤트 발생– 버튼을 클릭할 때– 텍스트필드에 문자를 타이핑할 때– 콤보박스에서 아이템을 선택할 때– 타이머가 타임아웃될 때 , 등등 ...

• 버튼 , 텍스트필드 등 GUI 콤포넌트들이 이벤트 소스 (source) 임

자바프로그래밍 강원대학교 3

Page 4: 9.  이벤트 처리 그래픽프로그래밍

이벤트 (Events)

• 프로그래머는 많은 이벤트 중 관심 있는 이벤트에 대해서만 필요한 반응을 보이도록 프로그램 작성

• 특정 GUI 콤포넌트에서 발생하는 특정 이벤트에 대해 어떤 반응을 보이도록 하려면 적절한 이벤트 리스너(listener) 를 만들어 이를 해당 콤포넌트에 등록해 줌

• 이벤트 리스너 = 이벤트 처리기

자바프로그래밍 강원대학교 4

Page 5: 9.  이벤트 처리 그래픽프로그래밍

이벤트 소스와 이벤트 리스너

• Event listener: – 이벤트가 발생될 때 그 사실을 통보받는 객체– 프로그래머에 의해 작성되는 클래스 객체– 이벤트가 발생되었을 때 해야 할 작업이 이곳에

정의되어 있음– 이벤트 리스너가 등록되지 않은 이벤트에 대해서는

아무 반응도 없게 됨• Event source:

– 어떤 컴포넌트에서 이벤트가 발생되면 그 컴포넌트에 등록된 모든 이벤트 리스너들에게 이벤트 발생 사실이 통보됨

자바프로그래밍 강원대학교 5

Page 6: 9.  이벤트 처리 그래픽프로그래밍

• 이벤트가 여러 리스너에게 전달될 수 있다 .• 한 리스너가 여러 소스로부터 이벤트를 받을 수

있다 .

이벤트 소스와 이벤트 리스너

자바프로그래밍 강원대학교 6

Page 7: 9.  이벤트 처리 그래픽프로그래밍

ActionListener 예

• 버튼을 클릭하면 action event 발생 ( 버튼 : 이벤트 소스 )

• 이에 대해 반응을 보이게 하려면 ActionListener 객체를 버튼에 등록해 줌 ( 이 ActionListener 객체가 이벤트 처리기임 )

• ActionListener 객체 = ActionListener 인터페이스를 구현한 객체

• 버튼 클릭에 따라 Action 이벤트가 발생하면 ActionListener 의 actionPerformed 메소드가 실행됨

public interface ActionListener { void actionPerformed(ActionEvent event); }

자바프로그래밍 강원대학교 7

Page 8: 9.  이벤트 처리 그래픽프로그래밍

Output

자바프로그래밍 강원대학교 8

버튼을 클릭하면Action 이벤트가 발생함 !

ActionLis-tener

Page 9: 9.  이벤트 처리 그래픽프로그래밍

File ButtonTester.java

public class ButtonViewer{ public static void main(String[] args) { JFrame frame = new JFrame(); JButton button = new JButton("Click me!"); frame.add(button); button.addActionListener(new ClickListener());

frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}

자바프로그래밍 강원대학교 9

이벤트 처리기( 버튼에서 발생하는 Action 이벤트를 처리함 )

Page 10: 9.  이벤트 처리 그래픽프로그래밍

ActionListener(Action 이벤트 처리기 ) 구현

import java.awt.event.ActionEvent;import java.awt.event.ActionListener;

public class ClickListener implements ActionListener{ public void actionPerformed(ActionEvent event) { System.out.println("I was clicked."); } }

• ClickListener 객체는 ActionListener 인터페이스를 구현하고 있음 (ClickListener 객체는 ActionListener 임 )

• ClickListener 객체를 이벤트 리스너로서 버튼에 등록해 주면 버튼 클릭 때마다 ClickListenr 의 actionPerformed 메소드가 실행됨

자바프로그래밍 강원대학교 10

Page 11: 9.  이벤트 처리 그래픽프로그래밍

public class ButtonViewer{ public static void main(String[] args){

JFrame frame = new JFrame();JButton button = new JButton("Click me!");frame.add(button);class ClickListener implements ActionListener{

public void actionPerformed(ActionEvent event){

System.out.println("I was clicked.");}

}ActionListener listener = new ClickListener();button.addActionListener(listener);frame.pack();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}}

local inner class

자바프로그래밍 강원대학교 11

이렇게 하는 것도 가능 !

Page 12: 9.  이벤트 처리 그래픽프로그래밍

예 2

자바프로그래밍 강원대학교 12

ActionLis-tener

Page 13: 9.  이벤트 처리 그래픽프로그래밍

public class ButtonViewer{ public static void main(String[] args){

JFrame frame = new JFrame();JPanel panel = new JPanel();JButton button = new JButton("Click me!");final JTextField textField = new JTextField(20);panel.add(button);panel.add(textField);frame.add(panel);class ClickListener implements ActionListener{

public void actionPerformed(ActionEvent event){textField.setText("I was clicked.");

} }ActionListener listener = new ClickListener();button.addActionListener(listener);frame.pack();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}}

local inner class

자바프로그래밍 강원대학교 13

Page 14: 9.  이벤트 처리 그래픽프로그래밍

public class ButtonViewer{ public static void main(String[] args){

JFrame frame = new JFrame();JPanel panel = new JPanel();JButton button = new JButton("Click me!");final JTextField textField = new JTextField(20);panel.add(button);panel.add(textField);frame.add(panel);class ClickListener implements ActionListener{

public void actionPerformed(ActionEvent event){textField.setText("I was clicked.");

} }...

}}

Local class 내에서 그 local class 를 포함하고 있는 메소드의 지역변수를 사용하려면그 지역변수가 final 로 선언되어 있어야 한다 .

자바프로그래밍 강원대학교 14

Page 15: 9.  이벤트 처리 그래픽프로그래밍

public class ButtonViewer{ public static void main(String[] args){

JFrame frame = new JFrame();JPanel panel = new JPanel();JButton button = new JButton("Click me!");final JTextField textField = new JTextField(20);panel.add(button);panel.add(textField);frame.add(panel);ActionListener listener = new

ClickListener(textField);button.addActionListener(listener);frame.pack();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}}

local inner class 를 사용하지 않는 경우와 비교

자바프로그래밍 강원대학교 15

Page 16: 9.  이벤트 처리 그래픽프로그래밍

public class ClickListener implements ActionListener{ClickListener(JTextField tf){

textField = tf;}public void actionPerformed(ActionEvent event){

textField.setText("I was clicked.");}JTextField textField;

}

local inner class 를 사용하지 않는 경우와 비교

자바프로그래밍 강원대학교 16

Page 17: 9.  이벤트 처리 그래픽프로그래밍

public class ButtonViewer{ public static void main(String[] args){

JFrame frame = new JFrame();JPanel panel = new JPanel();JButton button = new JButton("Click me!");final JTextField textField = new JTextField(20);panel.add(button);panel.add(textField);frame.add(panel);ActionListener listener = new ActionListener() {

public void actionPerformed(ActionEvent event){

textField.setText("I was clicked.");}

};button.addActionListener(listener);frame.pack();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);

}}

Anonymous inner class

자바프로그래밍 강원대학교 17

이렇게 하는 것도 가능 !

• ActionListener 인터페이스를 구현하는 클래스를 선언하면서 동시에 객체 구성

• 클래스 이름 없음

Page 18: 9.  이벤트 처리 그래픽프로그래밍

ActionListener listener = new ActionListener() {public void actionPerformed(ActionEvent

event){textField.setText("I was clicked.");

} };

Anonymous inner class

자바프로그래밍 강원대학교 18

ActionListener 인터페이스를 구현하는 클래스라는 선언

Page 19: 9.  이벤트 처리 그래픽프로그래밍

ActionListener listener = new MouseAdaptor() {public void mouseClicked(MouseEvent event)

{textField.setText("I was clicked.");

} };

Anonymous inner class

자바프로그래밍 강원대학교 19

MouseAdaptor 클래스를 확장하여 구현하는 클래스라는 선언 (서브클래스 )

Page 20: 9.  이벤트 처리 그래픽프로그래밍

예 3

• 버튼을 클릭할 때마다 이자가 더해지고 잔액이 화면에 표시됨

자바프로그래밍 강원대학교 20

Page 21: 9.  이벤트 처리 그래픽프로그래밍

리스너 구현

class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { double interest = account.getBalance() * INTEREST_RATE / 100; account.deposit(interest); label.setText("balance=" + account.getBalance()); } }

자바프로그래밍 강원대학교 21

Page 22: 9.  이벤트 처리 그래픽프로그래밍

File InvestmentViewer1.java

01: import java.awt.event.ActionEvent;02: import java.awt.event.ActionListener;03: import javax.swing.JButton;04: import javax.swing.JFrame;05: import javax.swing.JLabel;06: import javax.swing.JPanel;07: import javax.swing.JTextField;08: 09: /**10: This program displays the growth of an investment. 11: */12: public class InvestmentViewer113: { 14: public static void main(String[] args)15: { 16: JFrame frame = new JFrame();17:

자바프로그래밍 강원대학교 22

Page 23: 9.  이벤트 처리 그래픽프로그래밍

File InvestmentViewer1.java

18: // The button to trigger the calculation19: JButton button = new JButton("Add Interest");20: 21: // The application adds interest to this bank account22: final BankAccount account = new BankAccount(INITIAL_BALANCE);23: 24: // The label for displaying the results25: final JLabel label = new JLabel(26: "balance=" + account.getBalance());27: 28: // The panel that holds the user interface components29: JPanel panel = new JPanel();30: panel.add(button);31: panel.add(label); 32: frame.add(panel);33:

자바프로그래밍 강원대학교 23

Page 24: 9.  이벤트 처리 그래픽프로그래밍

File InvestmentViewer1.java34: class AddInterestListener implements ActionListener35: {36: public void actionPerformed(ActionEvent event)37: {38: double interest = account.getBalance() 39: * INTEREST_RATE / 100;40: account.deposit(interest);41: label.setText(42: "balance=" + account.getBalance());43: } 44: } // inner class 이므로 account, label 사용 가능 !45: 46: ActionListener listener = new AddInterestListener();47: button.addActionListener(listener);48: 49: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);50: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);51: frame.setVisible(true);52: }

자바프로그래밍 강원대학교 24

Page 25: 9.  이벤트 처리 그래픽프로그래밍

File InvestmentViewer1.java

53: 54: private static final double INTEREST_RATE = 10;55: private static final double INITIAL_BALANCE = 1000;56: 57: private static final int FRAME_WIDTH = 400;58: private static final int FRAME_HEIGHT = 100;59: }

자바프로그래밍 강원대학교 25

Page 26: 9.  이벤트 처리 그래픽프로그래밍

AddInterestListener 객체

actionPerformed() 메소드

등록 callback

재계산 및 디스플레이

자바프로그래밍 강원대학교 26

Page 27: 9.  이벤트 처리 그래픽프로그래밍

예 4

JTextField

자바프로그래밍 강원대학교 27

Page 28: 9.  이벤트 처리 그래픽프로그래밍

Processing Text Input

class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { double rate = Double.parseDouble(rateField.getText()); . . . } }

자바프로그래밍 강원대학교 28

Page 29: 9.  이벤트 처리 그래픽프로그래밍

File InvestmentViewer2.java01: import java.awt.event.ActionEvent;02: import java.awt.event.ActionListener;03: import javax.swing.JButton;04: import javax.swing.JFrame;05: import javax.swing.JLabel;06: import javax.swing.JPanel;07: import javax.swing.JTextField;08: 09: /**10: This program displays the growth of an investment. 11: */12: public class InvestmentViewer213: { 14: public static void main(String[] args)15: { 16: JFrame frame = new JFrame();17:

자바프로그래밍 강원대학교 29

Page 30: 9.  이벤트 처리 그래픽프로그래밍

File InvestmentViewer2.java18: // The label and text field for entering the //interest rate19: JLabel rateLabel = new JLabel("Interest Rate: ");20: 21: final int FIELD_WIDTH = 10;22: final JTextField rateField = new JTextField(FIELD_WIDTH);23: rateField.setText("" + DEFAULT_RATE);24: 25: // The button to trigger the calculation26: JButton button = new JButton("Add Interest");27: 28: // The application adds interest to this bank account29: final BankAccount account = new BankAccount(INITIAL_BALANCE);30: 31: // The label for displaying the results32: final JLabel resultLabel = new JLabel(33: "balance=" + account.getBalance());34: 자바프로그래밍 강원대학교 30

Page 31: 9.  이벤트 처리 그래픽프로그래밍

File InvestmentViewer2.java35: // The panel that holds the user interface components36: JPanel panel = new JPanel();37: panel.add(rateLabel);38: panel.add(rateField);39: panel.add(button);40: panel.add(resultLabel); 41: frame.add(panel);42: 43: class AddInterestListener implements ActionListener44: {45: public void actionPerformed(ActionEvent event)46: {47: double rate = Double.parseDouble(48: rateField.getText());49: double interest = account.getBalance() 50: * rate / 100;51: account.deposit(interest);

자바프로그래밍 강원대학교 31

Page 32: 9.  이벤트 처리 그래픽프로그래밍

File InvestmentViewer2.java52: resultLabel.setText(53: "balance=" + account.getBalance());54: } 55: }56: 57: ActionListener listener = new AddInterestListener();58: button.addActionListener(listener);59: 60: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);61: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);62: frame.setVisible(true);63: }64: 65: private static final double DEFAULT_RATE = 10;66: private static final double INITIAL_BALANCE = 1000;67: 68: private static final int FRAME_WIDTH = 500;69: private static final int FRAME_HEIGHT = 200;70: }

자바프로그래밍 강원대학교 32

Page 33: 9.  이벤트 처리 그래픽프로그래밍

타이머 이벤트 처리

자바프로그래밍 강원대학교 33

Page 34: 9.  이벤트 처리 그래픽프로그래밍

Processing Timer Events• javax.swing.Timer 는 일정 시간 간격으로

액션이벤트를 발생시킨다 . • 객체 상태를 일정 시간 간격으로 갱신하고자 할 때 사용• 타이머에게 액션이벤트 리스너를 등록해 놓으면

액션이벤트가 발생될 때마다 액션이벤트 리스너의 ac-tionPerformed 메소드가 호출됨 - callback!

class MyListener implements ActionListener{     void actionPerformed(ActionEvent event)   {      // 타이머에서 액션이벤트가 발생할 때마다 // 이곳에 적어주는 액션이 실행됨   }}

자바프로그래밍 강원대학교 34

Page 35: 9.  이벤트 처리 그래픽프로그래밍

Processing Timer Events

• 액션 리스너를 타이머에 등록함

MyListener listener = new MyListener();Timer t = new Timer(interval, listener);t.start(); // 타이머 쓰레드 시작

TimerMyListener

actionPerformed

등록

주기적으로 이벤트 발생actionPerformed 메소드 실행 (callback)

자바프로그래밍 강원대학교 35

Page 36: 9.  이벤트 처리 그래픽프로그래밍

Example: Countdown• Example: a timer that counts down to zero

자바프로그래밍 강원대학교 36

Page 37: 9.  이벤트 처리 그래픽프로그래밍

File TimeTester.java01: import java.awt.event.ActionEvent;02: import java.awt.event.ActionListener;03: import javax.swing.JOptionPane;04: import javax.swing.Timer;05: 06: /**07: This program tests the Timer class.08: */09: public class TimerTester10: {11: public static void main(String[] args)12: {13: class CountDown implements ActionListener14: {15: public CountDown(int initialCount)16: {17: count = initialCount;18: }

자바프로그래밍 강원대학교 37

Page 38: 9.  이벤트 처리 그래픽프로그래밍

File TimeTester.java

19: 20: public void actionPerformed(ActionEvent event)21: {22: if (count >= 0)23: System.out.println(count);24: if (count == 0)25: System.out.println("Liftoff!");26: count--;27: }28: 29: private int count;30: }31: 32: CountDown listener = new CountDown(10);33: 34: final int DELAY = 1000; // Milliseconds between // timer ticks

자바프로그래밍 강원대학교 38

Page 39: 9.  이벤트 처리 그래픽프로그래밍

File TimeTester.java

35: Timer t = new Timer(DELAY, listener);36: t.start();37: 38: JOptionPane.showMessageDialog(null, "Quit?");39: System.exit(0);40: }41: }

자바프로그래밍 강원대학교 39

Page 40: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

애니메이션 프로그램 기본 형식

class Mover implements ActionListener { public void actionPerformed(ActionEvent event) { // Move the rectangle } }

ActionListener listener = new Mover(); final int DELAY = 100; // Milliseconds between timer ticks Timer t = new Timer(DELAY, listener); t.start();

40

Page 41: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Accessing Surrounding Variables• Inner 클래스의 메소드에서는 바깥 클래스의 변수에 접근할 수

있음public static void main(String[] args) { . . . final Rectangle box = new Rectangle(5, 10, 20, 30);

class Mover implements ActionListener { public void actionPerformed(ActionEvent event) { // Move the rectangle box.translate(1, 1); } } . . . }

41

Page 42: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File TimeTester2.java

01: import java.awt.Rectangle;02: import java.awt.event.ActionEvent;03: import java.awt.event.ActionListener;04: import javax.swing.JOptionPane;05: import javax.swing.Timer;06: 07: /**08: This program uses a timer to move a rectangle once per second.09: */10: public class TimerTester211: {12: public static void main(String[] args)13: {14: final Rectangle box = new Rectangle(5, 10, 20, 30);15: 16: class Mover implements ActionListener17: {

42

Page 43: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File TimeTester2.java18: public void actionPerformed(ActionEvent event)19: {20: box.translate(1, 1);21: System.out.println(box);22: }23: }24: 25: ActionListener listener = new Mover();26: 27: final int DELAY = 100; // Milliseconds between timer ticks28: Timer t = new Timer(DELAY, listener);29: t.start();30: 31: JOptionPane.showMessageDialog(null, "Quit?");32: System.out.println("Last box position: " + box);33: System.exit(0);34: }35: }

43

Page 44: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File TimeTester2.java

java.awt.Rectangle[x=6,y=11,width=20,height=30] java.awt.Rectangle[x=7,y=12,width=20,height=30] java.awt.Rectangle[x=8,y=13,width=20,height=30] . . . java.awt.Rectangle[x=28,y=33,width=20,height=30] java.awt.Rectangle[x=29,y=34,width=20,height=30] Last box position: java.awt.Rectangle[x=29,y=34,width=20,height=30]

Output:

44

Page 45: 9.  이벤트 처리 그래픽프로그래밍

배치관리Layout Management

자바프로그래밍 강원대학교 45

Page 46: 9.  이벤트 처리 그래픽프로그래밍

배치 관리 Layout Management

• 컨테이너는 배치관리자 (layout manager) 를 갖는다 .

• 배치관리자– border layout – flow layout – grid layout

자바프로그래밍 강원대학교 46

Page 47: 9.  이벤트 처리 그래픽프로그래밍

Layout Management

• JPanel 은 기본으로 FlowLayout manager를 갖는다 .

• FlowLayout manager 는 컴포넌트를 옆으로 차례로 늘어 놓는다 .

• JPanel 이 다른 종류의 layout manager 를 사용하도록 할 수도 있다 .

JPanel panel1 = new Jpanel();

panel.setLayout(new BorderLayout());

자바프로그래밍 강원대학교 47

Page 48: 9.  이벤트 처리 그래픽프로그래밍

Border Layout

자바프로그래밍 강원대학교 48

Page 49: 9.  이벤트 처리 그래픽프로그래밍

Border Layout

• Frame ( 실제로는 frame 의 content pane) 의 기본 배치관리자는 BorderLayout

• 컴포넌트를 넣는 법

• 전체 컨테이너 면적을 꽉 채우도록 각 컴포넌트의 크기를 늘여 조절함

JPanel panel1 = new Jpanel();panel.setLayout(new BorderLayout()); panel.add(component, BorderLayout.NORTH);

자바프로그래밍 강원대학교 49

Page 50: 9.  이벤트 처리 그래픽프로그래밍

Grid Layout• 전체 영역을 격자형으로 구획하고 차례로 컴포넌트를

삽입• 컴포넌트들이 같은 크기를 갖도록 크기 조정

JPanel numberPanel = new JPanel(); numberPanel.setLayout(new GridLayout(4, 3)); numberPanel.add(button7); numberPanel.add(button8); numberPanel.add(button9); numberPanel.add(button4); . . .

자바프로그래밍 강원대학교 50

Page 51: 9.  이벤트 처리 그래픽프로그래밍

Swing Package

자바프로그래밍 강원대학교 51

Page 52: 9.  이벤트 처리 그래픽프로그래밍

Graphical User Interface (GUI) compo-nents

Abstract Window Toolkit (AWT) – "heavyweight" components– java.awt.Button– java.awt.Checkbox– java.awt.Dialog

Swing - "lightweight" components– javax.swing.JButton– javax.swing.JCheckBox– javax.swing.JDialog

자바프로그래밍 강원대학교 52

Page 53: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Swing Components

http://download.oracle.com/javase/tutorial/ui/features/components.html

53

Page 55: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Choices

• Radio buttons • Check boxes • Combo boxes

55

Page 56: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Radio Buttons

• Font sizes are mutually exclusive:

JRadioButton smallButton = new JRadioButton("Small"); JRadioButton mediumButton = new JRadioButton("Medium"); JRadioButton largeButton = new JRadioButton("Large");

// Add radio buttons into a ButtonGroup so that // only one button in group is on at any time ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton);

56

Page 57: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Radio Buttons

• Button group 은 버튼들을 가까이 모아 놓지는 않음 , 프로그래머가 알아서 버튼을 배치해야 함

• isSelected: 버튼이 선택됐는지 알아보기 위해 호출

• setSelected(true) 프레임을 화면이 보이기 전에 (setVisible(true)) 라디오버튼 하나에게 호출

(largeButton.isSelected()) size = LARGE_SIZE;

57

Page 58: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Borders ( 경계선 )

• 어느 컴포넌트에건 경계선을 넣을 수 있으나 주로 panel 에 사용됨

Jpanel panel = new JPanel ();panel.setBorder(new EtchedBorder ());

Panel.setBorder(new TitledBorder(new EtchedBorder(), “Size”));

58

Page 59: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Borders ( 경계선 )

59

Page 60: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Check Boxes

JCheckBox italicCheckBox = new JCheckBox("Italic");

60

Page 61: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Combo Boxes

• 선택지가 많을 때는 Combo Box 를 사용– 라디오 버튼에 비해 공간을 적게 차지하므로

• "Combo": combination of a list and a text field – The text field displays the name of the

current selection

61

Page 62: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Combo Boxes

• If combo box is editable, user can type own selection – Use setEditable method

• Add strings with addItem method:

JComboBox facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); . . .

62

Page 63: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Combo Boxes

• Get user selection with getSelectedItem (return type is Object)

• Select an item with setSelectedItem

String selectedString = (String) facenameCombo.getSelectedItem();

63

Page 64: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Radio Buttons, Check Boxes, and Combo Boxes

• 이 컴포넌트들은 아이템이 선택될 때 Action-Event 를 발생시킴

64

Page 65: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

An example: ChoiceFrame

65

Page 66: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Classes of the Font Choice Pro-gram

66

Page 67: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrameViewer.java

01: import javax.swing.JFrame;02: 03: /**04: This program tests the ChoiceFrame.05: */06: public class ChoiceFrameViewer07: { 08: public static void main(String[] args)09: { 10: JFrame frame = new ChoiceFrame();11: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);12: frame.setVisible(true); 13: }14: }15:

67

Page 68: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

001: import java.awt.BorderLayout;002: import java.awt.Font;003: import java.awt.GridLayout;004: import java.awt.event.ActionEvent;005: import java.awt.event.ActionListener;006: import javax.swing.ButtonGroup;007: import javax.swing.JButton;008: import javax.swing.JCheckBox;009: import javax.swing.JComboBox;010: import javax.swing.JFrame;011: import javax.swing.JLabel;012: import javax.swing.JPanel;013: import javax.swing.JRadioButton;014: import javax.swing.border.EtchedBorder;015: import javax.swing.border.TitledBorder;016:

68

Page 69: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

017: /**018: This frame contains a text field and a control panel019: to change the font of the text.020: */021: public class ChoiceFrame extends JFrame022: {023: /**024: Constructs the frame.025: */026: public ChoiceFrame()027: { 028: // Construct text sample029: sampleField = new JLabel("Big Java");030: add(sampleField, BorderLayout.CENTER);031:

69

Page 70: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

032: // This listener is shared among all components033: class ChoiceListener implements ActionListener034: { 035: public void actionPerformed(ActionEvent event)036: { 037: setSampleFont();038: }039: }040: 041: listener = new ChoiceListener();042: 043: createControlPanel();044: setSampleFont();045: setSize(FRAME_WIDTH, FRAME_HEIGHT);046: }047:

70

Page 71: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

048: /**049: Creates the control panel to change the font.050: */051: public void createControlPanel()052: {053: JPanel facenamePanel = createComboBox();054: JPanel styleGroupPanel = createCheckBoxes();055: JPanel sizeGroupPanel = createRadioButtons();056: 057: // Line up component panels058: 059: JPanel controlPanel = new JPanel();060: controlPanel.setLayout(new GridLayout(3, 1));061: controlPanel.add(facenamePanel);062: controlPanel.add(styleGroupPanel);063: controlPanel.add(sizeGroupPanel);064:

71

Page 72: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java065: // Add panels to content pane066: 067: add(controlPanel, BorderLayout.SOUTH);068: }069: 070: /**071: Creates the combo box with the font style choices.072: @return the panel containing the combo box073: */074: public JPanel createComboBox()075: {076: facenameCombo = new JComboBox();077: facenameCombo.addItem("Serif");078: facenameCombo.addItem("SansSerif");079: facenameCombo.addItem("Monospaced");080: facenameCombo.setEditable(true);081: facenameCombo.addActionListener(listener);082:

72

Page 73: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java083: JPanel panel = new JPanel();084: panel.add(facenameCombo);085: return panel;086: }087: 088: /**089: Creates the check boxes for selecting bold and // italic styles.090: @return the panel containing the check boxes091: */092: public JPanel createCheckBoxes()093: {094: italicCheckBox = new JCheckBox("Italic");095: italicCheckBox.addActionListener(listener);096: 097: boldCheckBox = new JCheckBox("Bold");098: boldCheckBox.addActionListener(listener);099:

73

Page 74: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

100: JPanel panel = new JPanel();101: panel.add(italicCheckBox);102: panel.add(boldCheckBox);103: panel.setBorder104: (new TitledBorder(new EtchedBorder(), "Style"));105: 106: return panel;107: }108: 109: /**110: Creates the radio buttons to select the font size111: @return the panel containing the radio buttons112: */113: public JPanel createRadioButtons()114: {115: smallButton = new JRadioButton("Small");116: smallButton.addActionListener(listener);

74

Page 75: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

117: 118: mediumButton = new JRadioButton("Medium");119: mediumButton.addActionListener(listener);120: 121: largeButton = new JRadioButton("Large");122: largeButton.addActionListener(listener);123: largeButton.setSelected(true);124: 125: // Add radio buttons to button group126: 127: ButtonGroup group = new ButtonGroup();128: group.add(smallButton);129: group.add(mediumButton);130: group.add(largeButton);131:

75

Page 76: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

132: JPanel panel = new JPanel();133: panel.add(smallButton);134: panel.add(mediumButton);135: panel.add(largeButton);136: panel.setBorder137: (new TitledBorder(new EtchedBorder(), "Size"));138: 139: return panel;140: }141: 142: /**143: Gets user choice for font name, style, and size144: and sets the font of the text sample.145: */146: public void setSampleFont()147: {

76

Page 77: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

148: // Get font name 149: String facename 150: = (String) facenameCombo.getSelectedItem();151: 152: // Get font style153: 154: int style = 0;155: if (italicCheckBox.isSelected()) 156: style = style + Font.ITALIC;157: if (boldCheckBox.isSelected()) 158: style = style + Font.BOLD;159: 160: // Get font size 161: 162: int size = 0;163:

77

Page 78: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

164: final int SMALL_SIZE = 24;165: final int MEDIUM_SIZE = 36;166: final int LARGE_SIZE = 48;167: 168: if (smallButton.isSelected()) 169: size = SMALL_SIZE;170: else if (mediumButton.isSelected()) 171: size = MEDIUM_SIZE;172: else if (largeButton.isSelected()) 173: size = LARGE_SIZE;174: 175: // Set font of text field176: 177: sampleField.setFont(new Font(facename, style, size));178: sampleField.repaint();179: }

78

Page 79: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File ChoiceFrame.java

180: 181: private JLabel sampleField;182: private JCheckBox italicCheckBox;183: private JCheckBox boldCheckBox;184: private JRadioButton smallButton;185: private JRadioButton mediumButton;186: private JRadioButton largeButton;187: private JComboBox facenameCombo;188: private ActionListener listener;189: 190: private static final int FRAME_WIDTH = 300;191: private static final int FRAME_HEIGHT = 400;192: }

79

Page 80: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Advanced Topic: Layout Management

80

Page 81: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Advanced Topic: Layout Management

81

Page 82: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Advanced Topic: Layout Management

82

Page 83: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Menus

• 프레임은 메뉴바를 가짐• 메뉴바는 메뉴를 가짐• 메뉴는 서브메뉴와 메뉴아이템을 가짐

83

Page 84: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Menus

84

Page 85: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Menu Items

• 메뉴에 서브메뉴와 메뉴아이템을 넣기 위해서는 메뉴의 add 메소드를 사용함

• 메뉴아이템은 서브메뉴를 갖지 않음• 메뉴아이템은 액션 이벤트를 발생시킴

JMenuItem fileExitItem = new JMenuItem("Exit"); fileMenu.add(fileExitItem);

85

Page 86: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Menu Items

• 메뉴아이템에는 액션리스너를 등록함

• 메뉴나 메뉴바에는 액션리스너를 등록하지 않음

fileExitItem.addActionListener(listener);

86

Page 87: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

예• 간단하고 일반적인 메뉴를 구축• 각 메뉴아이템으로부터의 이벤트를 처리• 각 메뉴 혹은 메뉴 그룹을 만들기 위해 별도의

메소드를 사용 – 읽기 쉽게– createFaceItem: creates menu item to

change the font face – createSizeItem – createStyleItem

87

Page 88: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrameViewer.java

01: import javax.swing.JFrame;02: 03: /**04: This program tests the MenuFrame.05: */06: public class MenuFrameViewer07: { 08: public static void main(String[] args)09: { 10: JFrame frame = new MenuFrame();11: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);12: frame.setVisible(true); 13: }14: }15:

88

Page 89: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

001: import java.awt.BorderLayout;002: import java.awt.Font;003: import java.awt.GridLayout;004: import java.awt.event.ActionEvent;005: import java.awt.event.ActionListener;006: import javax.swing.ButtonGroup;007: import javax.swing.JButton;008: import javax.swing.JCheckBox;009: import javax.swing.JComboBox;010: import javax.swing.JFrame;011: import javax.swing.JLabel;012: import javax.swing.JMenu;013: import javax.swing.JMenuBar;014: import javax.swing.JMenuItem;015: import javax.swing.JPanel;016: import javax.swing.JRadioButton;

89

Page 90: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

017: import javax.swing.border.EtchedBorder;018: import javax.swing.border.TitledBorder;019: 020: /**021: This frame has a menu with commands to change the font 022: of a text sample.023: */024: public class MenuFrame extends JFrame025: {026: /**027: Constructs the frame.028: */029: public MenuFrame()030: { 031: // Construct text sample 032: sampleField = new JLabel("Big Java");033: add(sampleField, BorderLayout.CENTER);034:

90

Page 91: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

035: // Construct menu 036: JMenuBar menuBar = new JMenuBar(); 037: setJMenuBar(menuBar);038: menuBar.add(createFileMenu());039: menuBar.add(createFontMenu());040: 041: facename = "Serif";042: fontsize = 24;043: fontstyle = Font.PLAIN;044: 045: setSampleFont();046: setSize(FRAME_WIDTH, FRAME_HEIGHT);047: }048: 049: /**050: Creates the File menu.051: @return the menu052: */

91

Page 92: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

053: public JMenu createFileMenu()054: {055: JMenu menu = new JMenu("File");056: menu.add(createFileExitItem());057: return menu;058: }059: 060: /**061: Creates the File->Exit menu item and sets its // action listener.062: @return the menu item063: */064: public JMenuItem createFileExitItem()065: {066: JMenuItem item = new JMenuItem("Exit"); 067: class MenuItemListener implements ActionListener068: {069: public void actionPerformed(ActionEvent event)

92

Page 93: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

070: {071: System.exit(0);072: }073: } 074: ActionListener listener = new MenuItemListener();075: item.addActionListener(listener);076: return item;077: }078: 079: /**080: Creates the Font submenu.081: @return the menu082: */083: public JMenu createFontMenu()084: {085: JMenu menu = new JMenu("Font");086: menu.add(createFaceMenu());

93

Page 94: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java087: menu.add(createSizeMenu());088: menu.add(createStyleMenu());089: return menu;090: } 091: 092: /**093: Creates the Face submenu.094: @return the menu095: */096: public JMenu createFaceMenu()097: {098: JMenu menu = new JMenu("Face");099: menu.add(createFaceItem("Serif"));100: menu.add(createFaceItem("SansSerif"));101: menu.add(createFaceItem("Monospaced"));102: return menu;103: } 104:

94

Page 95: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

105: /**106: Creates the Size submenu.107: @return the menu108: */109: public JMenu createSizeMenu()110: {111: JMenu menu = new JMenu("Size");112: menu.add(createSizeItem("Smaller", -1));113: menu.add(createSizeItem("Larger", 1));114: return menu;115: } 116: 117: /**118: Creates the Style submenu.119: @return the menu120: */121: public JMenu createStyleMenu()122: {

95

Page 96: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

123: JMenu menu = new JMenu("Style");124: menu.add(createStyleItem("Plain", Font.PLAIN));125: menu.add(createStyleItem("Bold", Font.BOLD));126: menu.add(createStyleItem("Italic", Font.ITALIC));127: menu.add(createStyleItem("Bold Italic", Font.BOLD 128: + Font.ITALIC));129: return menu;130: } 131: 132: 133: /**134: Creates a menu item to change the font face and // set its action listener.135: @param name the name of the font face136: @return the menu item137: */138: public JMenuItem createFaceItem(final String name)139: {

96

Page 97: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

140: JMenuItem item = new JMenuItem(name); 141: class MenuItemListener implements ActionListener142: {143: public void actionPerformed(ActionEvent event)144: {145: facename = name;146: setSampleFont();147: }148: } 149: ActionListener listener = new MenuItemListener();150: item.addActionListener(listener);151: return item;152: }153:

97

Page 98: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

154: /**155: Creates a menu item to change the font size156: and set its action listener.157: @param name the name of the menu item158: @param ds the amount by which to change the size159: @return the menu item160: */161: public JMenuItem createSizeItem(String name, final int ds)162: {163: JMenuItem item = new JMenuItem(name); 164: class MenuItemListener implements ActionListener165: {166: public void actionPerformed(ActionEvent event)167: {168: fontsize = fontsize + ds;169: setSampleFont();170: }171: }

98

Page 99: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

172: ActionListener listener = new MenuItemListener();173: item.addActionListener(listener);174: return item;175: }176: 177: /**178: Creates a menu item to change the font style179: and set its action listener.180: @param name the name of the menu item181: @param style the new font style182: @return the menu item183: */184: public JMenuItem createStyleItem(String name, final int style)185: {186: JMenuItem item = new JMenuItem(name); 187: class MenuItemListener implements ActionListener188: {

99

Page 100: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java

189: public void actionPerformed(ActionEvent event)190: {191: fontstyle = style;192: setSampleFont();193: }194: } 195: ActionListener listener = new MenuItemListener();196: item.addActionListener(listener);197: return item;198: }199: 200: /**201: Sets the font of the text sample.202: */203: public void setSampleFont()204: {

100

Page 101: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File MenuFrame.java205: Font f = new Font(facename, fontstyle, fontsize);206: sampleField.setFont(f);207: sampleField.repaint();208: }209: 210: private JLabel sampleField;211: private String facename;212: private int fontstyle;213: private int fontsize;214: 215: private static final int FRAME_WIDTH = 300;216: private static final int FRAME_HEIGHT = 400;217: }218: 219:

101

Page 102: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Text Areas

• 문자열을 여러 줄 보이고 싶을 때는 JTextArea 사용

• 행과 열 수를 지정

• setText: 화면에 나타날 문자열를 지정• append: 기존 문자열에 추가

final int ROWS = 10; final int COLUMNS = 30; JTextArea textArea = new JTextArea(ROWS, COLUMNS);

102

Page 103: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Text Areas

• 줄바꿈을 위해서는 newline 문자 사용

• 사용자가 편집을 하지 못하게 하려면

textArea.append(account.getBalance() + "\n");

textArea.setEditable(false); // program can call setText and append to change it

103

Page 104: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Text Areas

To add scroll bars to a text area:

JTextArea textArea = new JTextArea(ROWS, COLUMNS); JScrollPane scrollPane = new JScrollPane(textArea);

104

Page 105: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Text Areas

105

Page 106: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File TextAreaViewer.java

01: import java.awt.BorderLayout;02: import java.awt.event.ActionEvent;03: import java.awt.event.ActionListener;04: import javax.swing.JButton;05: import javax.swing.JFrame;06: import javax.swing.JLabel;07: import javax.swing.JPanel;08: import javax.swing.JScrollPane;09: import javax.swing.JTextArea;10: import javax.swing.JTextField;11: 12: /**13: This program shows a frame with a text area that 14: displays the growth of an investment. 15: */16: public class TextAreaViewer17: {

106

Page 107: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File TextAreaViewer.java18: public static void main(String[] args)19: { 20: JFrame frame = new JFrame();21: 22: // The application adds interest to this bank account23: final BankAccount account = new BankAccount(INITIAL_BALANCE);24: // The text area for displaying the results25: final int AREA_ROWS = 10;26: final int AREA_COLUMNS = 30;27: 28: final JTextArea textArea = new JTextArea(29: AREA_ROWS, AREA_COLUMNS);30: textArea.setEditable(false);31: JScrollPane scrollPane = new JScrollPane(textArea);32: 33: // The label and text field for entering the // interest rate

107

Page 108: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File TextAreaViewer.java34: JLabel rateLabel = new JLabel("Interest Rate: "); 35: 36: final int FIELD_WIDTH = 10;37: final JTextField rateField = new JTextField(FIELD_WIDTH);38: rateField.setText("" + DEFAULT_RATE);39: 40: // The button to trigger the calculation41: JButton calculateButton = new JButton("Add Interest");42: 43: // The panel that holds the input components44: JPanel northPanel = new JPanel();45: northPanel.add(rateLabel);46: northPanel.add(rateField);47: northPanel.add(calculateButton);48: 49: frame.add(northPanel, BorderLayout.NORTH);50: frame.add(scrollPane); 51:

108

Page 109: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File TextAreaViewer.java

52: class CalculateListener implements ActionListener53: {54: public void actionPerformed(ActionEvent event)55: {56: double rate = Double.parseDouble(57: rateField.getText());58: double interest = account.getBalance() 59: * rate / 100;60: account.deposit(interest);61: textArea.append(account.getBalance() + "\n");62: } 63: }64: 65: ActionListener listener = new CalculateListener();66: calculateButton.addActionListener(listener);67:

109

Page 110: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File TextAreaViewer.java

68: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);69: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);70: frame.setVisible(true);71: }72: 73: private static final double DEFAULT_RATE = 10;74: private static final double INITIAL_BALANCE = 1000;75: 76: private static final int FRAME_WIDTH = 400;77: private static final int FRAME_HEIGHT = 200;78: }

110

Page 111: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Swing Documentation 을 찾아보는 법

• 복잡하고 미세한 표현을 위해서는 Swing documentation 을 참고해야 함

• 매우 방대한 문서임

111

Page 112: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Example: A Color Mixer

• RGB 색깔을 배합하여 임의의 색깔을 보임

112

Page 113: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Example: A Color Mixer

• slider 라는 컴포넌트가 있다는 사실을 어떻게 아는가 ? – Swing component 책을 사서 본다 .– JDK 에 들어 있는 sample application 을

돌려본다 .– J 로 시작하는 모든 클래스를 살펴본다 .

• JSlider

113

Page 114: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Example: A Color Mixer

• 다음에 알아야 할 것들– JSlider 는 어떻게 구성하는가 ? – 사용자가 슬라이더를 움직였을 때 그 사실을

어떻게 알 수 있나 ?– 사용자가 슬라이더를 어느 값에 세트했는지

어떻게 알 수 있나 ?• 기타

– 슬라이더에 눈금은 어떻게 만드나 ? 등등

114

Page 115: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

Example: A Color Mixer

• JSlider class 에는 50개의 고유 메소드와 250개의 상속한 메소드가 있음

• 어떤 메소드는 그 설명이 엄청 어려워 무슨 말인지 이해할 수 없음– 기본적인 핵심만 이해하고 이용하면 됨– 지나치게 복잡하고 지엽적인 내용에

함몰되지 않는 것이 좋음

115

Page 116: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

JSlider 는 어떻게 구성하나 ?

• API documentation 을 찾아봄• 여섯개의 구성자• 그 중 한두 개 정도 읽어봄• 가장 간단한 것과 가장 복잡한 것의 중간 쯤

되는 것이 통상 효용이 높음

116

Page 117: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

JSlider 는 어떻게 구성하나 ?

• 지나치게 제한적

Range 0 to 100, initial value of 50 • 지나치게 복잡

• 실용적

public JSlider()

public JSlider(BoundedRangeModel brm)

public JSlider(int min, int max, int value)

117

Page 118: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

사용자가 슬라이더를 움직였을 때 그 사실을 어떻게 알 수 있나 ?

• addActionListener 메소드가 없음• 아래 메소드가 있음

• ChangeListener 를 클릭하여 자세히 알아봄• 하나의 메소드만을 가짐

public void addChangeListener(ChangeListener l)

void stateChanged(ChangeEvent e)

118

Page 119: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

사용자가 슬라이더를 움직였을 때 그 사실을 어떻게 알 수 있나 ?

• 사용자가 슬라이더를 움질이면 이 메소드가 호출될 것임

• ChangeEvent 는 무엇인가 ?– 슈퍼클래스인 EventObject 로부터 get-

Source 메소드를 상속함– getSource: 어떤 컴포넌트에서 이벤트가

만들어졌는지 알려줌

119

Page 120: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

사용자가 슬라이더를 움직였을 때 그 사실을 어떻게 알 수 있나 ?

• 아래와 같이 하면 될 것이라는 것을 알게 됨– 슬라이더에 change event listener 를

등록함– 슬라이더가 변경될 때마다 stateChanged

메소드가 호출됨– 새로 설정된 슬라이더 값을 읽음– 색깔 값을 계산함– 칼라 패널을 repaint

120

Page 121: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

사용자가 슬라이더를 어느 값에 세트했는지 어떻게 알 수 있나 ?

• JSlider 클래스에서 get 으로 시작하는 메소드를 살펴보면 아래 메소드를 찾을 수 있음

public int getValue()

121

Page 122: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

The Components of the Slid-erFrame

122

Page 123: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File SliderFrameViewer.java

01: import javax.swing.JFrame;02: 03: public class SliderFrameViewer04: { 05: public static void main(String[] args)06: { 07: SliderFrame frame = new SliderFrame();08: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);09: frame.setVisible(true);10: }11: }12:

123

Page 124: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File SliderFrame.java

01: import java.awt.BorderLayout;02: import java.awt.Color;03: import java.awt.GridLayout;04: import javax.swing.JFrame;05: import javax.swing.JLabel;06: import javax.swing.JPanel;07: import javax.swing.JSlider;08: import javax.swing.event.ChangeListener;09: import javax.swing.event.ChangeEvent;10: 11: public class SliderFrame extends JFrame12: { 13: public SliderFrame()14: { 15: colorPanel = new JPanel();16:

124

Page 125: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File SliderFrame.java

17: add(colorPanel, BorderLayout.CENTER);18: createControlPanel();19: setSampleColor();20: setSize(FRAME_WIDTH, FRAME_HEIGHT);21: }22: 23: public void createControlPanel()24: {25: class ColorListener implements ChangeListener26: { 27: public void stateChanged(ChangeEvent event)28: { 29: setSampleColor();30: }31: } 32:

125

Page 126: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File SliderFrame.java

33: ChangeListener listener = new ColorListener();34: 35: redSlider = new JSlider(0, 100, 100);36: redSlider.addChangeListener(listener);37: 38: greenSlider = new JSlider(0, 100, 70);39: greenSlider.addChangeListener(listener);40: 41: blueSlider = new JSlider(0, 100, 70);42: blueSlider.addChangeListener(listener);43: 44: JPanel controlPanel = new JPanel();45: controlPanel.setLayout(new GridLayout(3, 2));46: 47: controlPanel.add(new JLabel("Red"));48: controlPanel.add(redSlider);49:

126

Page 127: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File SliderFrame.java 50: controlPanel.add(new JLabel("Green"));51: controlPanel.add(greenSlider);52: 53: controlPanel.add(new JLabel("Blue"));54: controlPanel.add(blueSlider);55: 56: add(controlPanel, BorderLayout.SOUTH); 57: }58: 59: /**60: Reads the slider values and sets the panel to61: the selected color.62: */63: public void setSampleColor()64: { 65: // Read slider values66:

127

Page 128: 9.  이벤트 처리 그래픽프로그래밍

자바프로그래밍 강원대학교

File SliderFrame.java 67: float red = 0.01F * redSlider.getValue();68: float green = 0.01F * greenSlider.getValue();69: float blue = 0.01F * blueSlider.getValue();70: 71: // Set panel background to selected color72: 73: colorPanel.setBackground(new Color(red, green, blue));74: colorPanel.repaint();75: }76: 77: private JPanel colorPanel;78: private JSlider redSlider;79: private JSlider greenSlider;80: private JSlider blueSlider;81: 82: private static final int FRAME_WIDTH = 300;83: private static final int FRAME_HEIGHT = 400;84: }

128

Page 129: 9.  이벤트 처리 그래픽프로그래밍

Nested Classes

자바프로그래밍 강원대학교 129

Page 130: 9.  이벤트 처리 그래픽프로그래밍

Nested Classes

class OuterClass { ... class NestedClass { ... }}

A nested class is a member of its enclosing class

자바프로그래밍 강원대학교 130

Page 131: 9.  이벤트 처리 그래픽프로그래밍

Why Use Nested Classes?

• It is a way of logically grouping classes that are only used in one place.

• It increases encapsulation.

• Nested classes can lead to more readable and maintainable code.

자바프로그래밍 강원대학교 131

Page 132: 9.  이벤트 처리 그래픽프로그래밍

Static nested classes, Non-static nested classes

class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... }}

자바프로그래밍 강원대학교 132

Non-static nested classes are called inner classes

Page 133: 9.  이벤트 처리 그래픽프로그래밍

Static nested classes, Non-static nested classes

• Non-static nested classes (inner classes) have ac-cess to other members of the enclosing class, even if they are declared private

• Static nested classes do not have access to other members of the enclosing class

자바프로그래밍 강원대학교 133

Page 134: 9.  이벤트 처리 그래픽프로그래밍

Static Nested Classes

• A static nested class is behaviorally a top-level class that has been nested in another.

• OuterClass.StaticNestedClass nestedObject = new

OuterClass.StaticNestedClass();

자바프로그래밍 강원대학교 134

Page 135: 9.  이벤트 처리 그래픽프로그래밍

Static Nested Classes• Cannot refer directly to instance variables or

methods defined in its enclosing class — can use them only through an object reference.

자바프로그래밍 강원대학교 135

Page 136: 9.  이벤트 처리 그래픽프로그래밍

무엇이 잘못인가 ?

public class Problem {String s;static class Inner {

void testMethod() { s = "Set from Inner";}

}}

자바프로그래밍 강원대학교 136

refering directly to the in-stance variable defined in its enclosing class

Page 137: 9.  이벤트 처리 그래픽프로그래밍

public class Problem {String s;static class Inner {

void testMethod() { Problem p = new Problem();

p.s = "Set from Inner";}

}}

자바프로그래밍 강원대학교 137

refering to the instance variable defined in its en-closing class through an object reference

Page 138: 9.  이벤트 처리 그래픽프로그래밍

Inner Classes• Inner class is associated with an instance of its

enclosing class and has direct access to that ob-ject's methods and fields

class OuterClass { ... class InnerClass { ... } }

Objects that are instances of an in-ner class exist within an instance of the outer class

Instance of Inner-Class

Instance of Out-erClass

자바프로그래밍 강원대학교 138

Page 139: 9.  이벤트 처리 그래픽프로그래밍

Inner Classes

• To instantiate an inner class– first instantiate the outer class– create the inner object within the outer object

OuterClass outerObject = new OuterClass();OuterClass.InnerClass innerObject =

outerObject.new InnerClass();

자바프로그래밍 강원대학교 139

Page 140: 9.  이벤트 처리 그래픽프로그래밍

public class Class1 {protected InnerClass1 ic;public Class1() {

ic = new InnerClass1();}public void displayStrings() {

System.out.println(ic.getString() + ".");}static public void main(String[] args) {

Class1 c1 = new Class1();c1.displayStrings();

}protected class InnerClass1 {

public String getString() {return "InnerClass1: getString invoked";

}}

}자바프로그래밍 강원대학교 140

Page 141: 9.  이벤트 처리 그래픽프로그래밍

Inner Classes

Two special kinds of inner classes

• Local inner classes – 메소드 내부에 선언된 inner class

• Anonymous inner classes– 이름 없이 메소드 내부에 선언된 inner class

자바프로그래밍 강원대학교 141