본문 바로가기

학습공간/JAVA, 객체지향프로그래밍

[7주차] 자바의 이벤트 처리

반응형

객체지향프로그래밍 10장 자바의 이벤트 처리

실습문제 1번 마우스 업다운 이벤트 (MyMouseListener)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class ListenerSample extends JFrame{    
    ListenerSample(){                    // 프레임 초기화
        setTitle("마우스 올리기 내리기");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JLabel la = new JLabel("사랑해");        // 라벨 초기화
        MyMouseListener listener = new MyMouseListener();    // 이벤트객체 
        la.addMouseListener(listener);            // 라벨에 이벤트 등록
        
        add(la);                        // 프레임에 라벨 부착
        setSize(300,150);
        setVisible(true);
        }
    public static void main(String[] args) {
        new ListenerSample();
    }
}
 
class MyMouseListener extends MouseAdapter{            // 이벤트 리스너 구현
    public void mouseEntered(MouseEvent arg0) {    // 마우스가 들어올 때
        JLabel la = (JLabel)arg0.getSource();    // 현재 라벨 소스를 얻어냄
        la.setText("Love Java");            // 라벨 텍스트 변경
    }
 
    public void mouseExited(MouseEvent arg0) {    // 마우스가 나갈 때
        JLabel la = (JLabel)arg0.getSource();    // 현재 라벨 소스를 얻어냄
        la.setText("사랑해");            // 라벨 텍스트 변경
    }
}
cs

실습문제 2번 마우스 드래깅 이벤트 (MyMouseListener)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class ListenerSample2 extends JFrame{
    JPanel contentPane = new JPanel();    // 컨텐츠 팬 생성
    
    ListenerSample2(){        // 프레임 초기화
        setTitle("드래깅동안 YELLOW");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
        setContentPane(contentPane);    // 프레임에 팬 부착
        contentPane.setLayout(null);    
        contentPane.addMouseMotionListener(new MyMouseListener2());    
                                // 이벤트 객체 등록
        contentPane.setBackground(Color.green);    // 팬 색깔 초기화 (그린)
        setSize(200,200);
        setVisible(true);
    }
    public static void main(String[] args) {
        new ListenerSample2();
    }
}
 
class MyMouseListener2 implements MouseMotionListener{    // 이벤트 리스너 구현
    public void mouseDragged(MouseEvent e) {    // 드래그 할 때
        JPanel contentPane = (JPanel)e.getSource();    // 현재 소스 얻어냄
        contentPane.setBackground(Color.yellow);    // 팬 색깔 (옐로우)
    }
 
    public void mouseMoved(MouseEvent e) {    // 마우스 움직일 때
        JPanel contentPane = (JPanel)e.getSource();    // 현재 소스 얻어냄
        contentPane.setBackground(Color.green);    // 팬 색깔 (그린)
    }    
}
cs

실습문제 3번 키보드 방향키 이벤트 (MyKeyListener) - 글자 반전

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.awt.event.*;
import javax.swing.*;
 
public class Reverse extends JFrame{
    JPanel contentPane = new JPanel();    // 팬으로 사용할 패널
    JLabel KeyMessage;             // 1개의 컴포넌트 (라벨)
    Reverse()    // 프레임 초기화
    {
        setTitle("Left 키로 문자열 반전");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setContentPane(contentPane);    // 프레임에 팬 부착 및 등록
        contentPane.addKeyListener(new MyKeyListener());
        KeyMessage = new JLabel("Love Java");    // 라벨 초기화
        contentPane.add(KeyMessage);        // 팬에 라벨 부착
        setSize(300,150);
        setVisible(true);
        contentPane.requestFocus();    // 키 입력시 팬에 포커스 지정
    }
    class MyKeyListener extends KeyAdapter{    // 이벤트 리스너 구현
        public void keyPressed(KeyEvent e) {    // key 입력 할 때
            int KeyCode = e.getKeyCode();
            StringBuffer str = new StringBuffer();
            if(e.getKeyText(KeyCode) == "Left"){    // 왼쪽방향키 일 때
                str.append(KeyMessage.getText());
                            // String-> StringBuffer
                str.reverse();        // 값의 반전
                KeyMessage.setText(((Object)str).toString());    
                            // StringBuffer의 값
            }
        }
    }
    public static void main(String[] args) {
        new Reverse();
    }
}
cs

실습문제 4번 키보드 방향키 이벤트 (MyKeyListener) - 글자 이동

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.awt.event.*;
import javax.swing.*;
 
public class Shift extends JFrame{
    JPanel contentPane = new JPanel();    // 팬으로 사용할 패널
    JLabel KeyMessage;             // 1개의 컴포넌트 (라벨)
    Shift()        // 프레임 초기화
    {
        setTitle("Left 키로 문자열 이동");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setContentPane(contentPane);    // Frame에 팬 부착 및 등록
        contentPane.addKeyListener(new MyKeyListener());
 
        KeyMessage = new JLabel("Love Java");    // 라벨 초기화
        contentPane.add(KeyMessage);    // 팬에 라벨 부착
        setSize(300,150);
        setVisible(true);
 
        contentPane.requestFocus();    // 키 입력 시 팬에 포커스 지정
    }
    class MyKeyListener extends KeyAdapter{
        public void keyPressed(KeyEvent e) {
            int KeyCode = e.getKeyCode();    
            if(e.getKeyText(KeyCode) == "Left"){    // 왼쪽 키 입력 시
                String str = new String();
                str = KeyMessage.getText();
                str = str.substring(19)+str.substring(01);
                KeyMessage.setText(str);
            }
        }
    }
    public static void main(String[] args) {
        new Shift();
    }
}
cs

실습문제 5번 키보드 특수키 이벤트 (MyKeyListener) - 글자 폰트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
 
public class Fontsize extends JFrame{
    JPanel contentPane = new JPanel();    // 팬으로 사용할 패널
    JLabel KeyMessage;             // 1개의 컴포넌트
    Fontsize()
    {
        setTitle("+,- 키로 폰트 크기 조절");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setContentPane(contentPane);        // 프레임에 팬 부착 및 등록
        contentPane.addKeyListener(new MyKeyListener());
        KeyMessage = new JLabel("Love Java");    // 라벨 초기화    
        KeyMessage.setFont(new Font("Arial", Font.PLAIN, 10));     // Fntsize10
        contentPane.add(KeyMessage);    // 팬에 라벨 부착
        setSize(300,150);
        setVisible(true);
        contentPane.requestFocus();    // 키 입력 시 포커스 팬에 지정
    }
    class MyKeyListener extends KeyAdapter{
        public void keyPressed(KeyEvent e) {
        char KeyChar = e.getKeyChar();
        if(KeyChar == '+'){    // 폰트사이즈 확대
            Font f = KeyMessage.getFont();
            int size = f.getSize();
            KeyMessage.setFont(new Font("Arial",Font.PLAIN, size+5));
        }
        if(KeyChar == '-'){    // 폰트사이즈 축소
            Font f = KeyMessage.getFont();
            int size = f.getSize();
            if(size > 5)    // 단, 5 이하에서는 줄어들지 않도록 함
              KeyMessage.setFont(new Font("Arial",Font.PLAIN, size-5));
            }
        }
    }
    public static void main(String[] args) {
        new Fontsize();
    }
}
 
cs

실습문제 6번 마우스 클릭 이벤트 (MyMouseListener) - 랜덤 라벨

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class Click extends JFrame{
    JPanel contentPane = new JPanel();    // 팬으로 사용할 패널
    JLabel KeyMessage;             // 1개의 컴포넌트
    
    Click(){
        setTitle("클릭 연습 용 응용프로그램");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
        contentPane.setLayout(null);    // 패널 레이아웃 초기화
        setContentPane(contentPane);    // 프레임에 팬 부착(1)
        contentPane.addMouseListener(new MyMouseListener()); // 등록
        
        KeyMessage = new JLabel("C");        // 라벨 초기화
        KeyMessage.setLocation(100100);    // 초기 위치 100, 100
        KeyMessage.setSize(2020);        // null일경우 초기화 필수
        contentPane.add(KeyMessage);    // 팬에 라벨 부착(2)
        
        setSize(300,300);
        setVisible(true);
    }
    class MyMouseListener extends MouseAdapter{
        public void mouseClicked(MouseEvent arg0) {    // 마우스 클릭 시
            int x = (int)(Math.random()*200);    
            int y = (int)(Math.random()*200);
            KeyMessage.setLocation(x, y);    // 랜덤 좌표에 라벨 출력
        }        
    }
    public static void main(String[] args) {
        new Click();
    }    
}
cs

겜블링 게임 만들기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
 
public class Game extends JFrame{
    JPanel GamePane1;                  // 게임팬 (패널)
    JLabel []la={new JLabel("0"), new JLabel("0"), new JLabel("0")};
    JLabel state = new JLabel("시작합니다.");      // 라벨 3개 & 상태메세지(라벨)
 
    Game(){            // 프레임 초기화
        setTitle("Open Challenge 10");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GamePane1 = new JPanel();    // 게임팬 생성
        GamePane1.setLayout(null);    // 레이아웃 (널)
        setContentPane(GamePane1);    // 프레임에 게임팬 부착
        GamePane1.addKeyListener(new MyKeyListener());  // 이벤트 등록
        
        for(int i=0; i<3; i++){
            la[i].setSize(80,50);    // null일때 라벨 사이즈 (필수)
            la[i].setLocation(100*(i+1), 50);        // 각 라벨 위치
            la[i].setBackground(Color.magenta);    // 라벨 색깔
            la[i].setForeground(Color.yellow);    // 라벨 내용 색깔
            
            la[i].setFont(new Font("Arial",Font.PLAIN, 40));
            la[i].setOpaque(true);
            
            GamePane1.add(la[i]);         // 팬에 라벨 부착            
        }
 
        state.setSize(80,80);        // 상태메시지 크기와 위치
        state.setLocation(200160);
        GamePane1.add(state);    // 상태메시지 (라벨) 부착
        
        setSize(500400);    // 팬 사이즈
        setVisible(true);
        
        GamePane1.requestFocus();    // 키 입력시 팬에 포커스 지정
    }
 
    class MyKeyListener extends KeyAdapter{    // 이벤트 리스너 구현
        public void keyPressed(KeyEvent arg0) {
            if(arg0.getKeyChar() == '\n'){    // Enter 입력 시
                int x = (int)(Math.random()*5);
                int y = (int)(Math.random()*5);
                int z = (int)(Math.random()*5);
                la[0].setText(Integer.toString(x));
                la[1].setText(Integer.toString(y));
                la[2].setText(Integer.toString(z));
                
                if(x == y && y == z)
                    state.setText("축하합니다!!");
                else
                    state.setText("아쉽군요");
            }
        }
    }
    public static void main(String[] args) {
        new Game();
    }
}
cs

 

반응형

'학습공간 > JAVA, 객체지향프로그래밍' 카테고리의 다른 글

[9주차] JDBC 실습 Ⅱ  (0) 2019.11.28
[8주차] JDBC 실습Ⅰ  (0) 2019.11.28
[6주차] GUI 실습  (0) 2019.11.28
[5주차] 제네릭과 컬렉션  (0) 2019.11.28
[4주차] 상속  (0) 2019.11.28