13. GUI_Event 예제

2021. 8. 27. 22:55· 국기훈련과정/JAVA 복습노트

1. 프레임의 특정 위치에 마우스 버튼을 클릭하면 해당 위치로 글자를 옮기는 작업.

 

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
public class Ex33_Event extends JFrame {
    
    public Ex33_Event() {
        setTitle("글자 이동 이벤트");
        JPanel container = new JPanel();        
        //1.컴포넌트 만들기
        JLabel label = new JLabel("JAVA");        
        //new Font("글자체", "효과", "글자크기")
        //글자체: 컴퓨터에 설치된 글자체 사용 가능.
        // 효과: Font.BOLD /Font.ITAIC / Font.PLAIN
        label.setFont(new Font("굴림체", Font.BOLD , 30));        
        //2.컨테이너에 컴포넌트 올리기
        container.add(label);        
        //3. 프레임에 컨테이너 올리기
        add(container);
        setBounds(200, 200, 300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);        
        //4. 이벤트 처리 - 컨테이너에서 특정 영역에 마우스 클릭 시 이벤트 처리
        container.addMouseListener(new MouseListener() {            
            //눌려진 마우스 버튼이 떼질 때
            @Override
            public void mouseReleased(MouseEvent e) { }            
            //마우스 버튼이 눌려질 때
            @Override
            public void mousePressed(MouseEvent e) {
                int x = e.getX(); //마우스 버튼이 눌려질 때의 x 좌표 값
                int y = e.getY(); //y좌표 값
                label.setLocation(x, y); //라벨의 위치 지정.                
            }            
            //컴포넌트 위에 올라왔던 마우스가 해당 컴포넌트를 떠날 때
            @Override
            public void mouseExited(MouseEvent e) { }            
            //컴포넌트 위에 마우스가 올라왔을 때
            @Override
            public void mouseEntered(MouseEvent e) { }            
            //마우스 버튼이 클릭되었을 때
            @Override
            public void mouseClicked(MouseEvent e) { }
        });
        
    }
Colored by Color Scripter
cs

.setFont(new Font("글자체", "효과", "글자크기")

좌표값 얻기

.getX(); .getY(); 

위치 지정

.setLocation(x, y);

 

2. 키보드 버튼 입력을 감지하는 예제.

 

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
public class Ex34_Event extends JFrame {
    
    public Ex34_Event() {
        setTitle("키 이벤트 처리");
        JPanel container = new JPanel();
        //1. 컴포넌트 만들기
        JLabel label = new JLabel();
        //2. 컨테이너에 컴포넌트 넣기
        container.add(label);
        //3. 프레임에 컨테이너 넣기
        add(container);        
        /*
         * **중요**
         * 키 이벤트는 포커스가 위치해 있어야 이벤트가 발생함.
         * 강제적으로 포커스를 설정해 줘야 함.
         * 키 이벤트는 포커스를 받을 수 있는 컴포넌트를 우선적으로
         * 입력받기 위해 setFocusable(true)가 필요.
         */
        container.setFocusable(true);
        
        setBounds(200, 200, 500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        
        /*
         * 4. 이벤트 처리
         * 컨테이너에서 이벤트 발생 시 이벤트 처리    
         */
        container.addKeyListener(new KeyListener() {            
            //키보드 자판의 문자가 눌렸을 때 실행되는 메서드
            @Override
            public void keyTyped(KeyEvent e) {}            
            //눌렀다가 뗄 때
            @Override
            public void keyReleased(KeyEvent e) {
                String str = KeyEvent.getKeyText(e.getKeyCode());
                label.setText(str + "키가 입력 되었습니다.");                
                if(e.getKeyCode() == KeyEvent.VK_F1) {
                    container.setBackground(Color.BLUE);                    
                }else if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    container.setBackground(Color.YELLOW);
                }                
            }
            //눌려졌을 때
            @Override
            public void keyPressed(KeyEvent e) {}
        });
    }
Colored by Color Scripter
cs

 

키 이벤트를 이용할 경우에는 컴포넌트가 들어있는 컨테이너에 .setFocusable(true)를 해주어야 작동함.

 

3. 다이얼로그 이용.

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
61
62
63
64
65
66
67
68
69
70
71
72
/*
 * 다이얼로그
 * -다이얼로그는 보여주고자 하는 내용을 스크린에 출력하고, 사용자로부터 입력을 받는 대화상자.
 * 
 * 팝업 당얼로그
 * -사용자에게 메세지를 전달하거나 간단한 문자열을 입력 받는 유용한 다이ㅣ얼로그임.
 * 1)입력 다이얼로그 : JOptionPane.showInputDialog()
 *                     ==> 보통 한 줄 문자열을 입력 받는 다이얼로그.
 * 2)확인 다이얼로그 : JOptionPane.showConfirmDialog()
 *                     ==> 사용자로부터 확인 / 취소를 입력받는 다이얼로그
 * 3)메세지 다이얼로그 : JOptionPane.showMessageDialog()
 *                     ==> 사용자에게 문자열 메세지를 출력하기 위한 다이얼로그
 * 
 */
 
public class Ex36_Event extends JFrame {
    
    public Ex36_Event() {
        setTitle("다이얼로그 예제");
        JPanel container = new JPanel();
        //1. 컴포넌트를 만들어보자.
        JButton inputBtn = new JButton("Input Name");
        JButton confirmBtn = new JButton("Confirm");
        JButton messageBtn = new JButton("Message");
        JTextField field = new JTextField(20);
        //2.컨테이너에 컴포넌트 올리기
        container.add(inputBtn); container.add(confirmBtn); 
        container.add(messageBtn); container.add(field);
        //3.프레임에 컨테이너를 올려야 한다.
        add(container);
        setBounds(200, 200, 500, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        //4.이벤트 처리
        inputBtn.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                // 입력 다이얼로그 생성
                String name = JOptionPane.showInputDialog("이름을 입력하세요");
                if(name != null) {
                    //사용자가 입력한 문자열을 텍스트필드 컴포넌트에 출력하는 메서드.
                    field.setText(name);
                }
            }
        });
        
        confirmBtn.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                // 확인 다이얼로그 창 생성
                int result = JOptionPane.showConfirmDialog
                        (null, "계속하실 건가요?", "Confirm", JOptionPane.YES_NO_OPTION);
                
                if(result == JOptionPane.YES_OPTION) {
                    field.setText("Yes");
                }else {
                    field.setText("No");
                }
            }
        });
        
        messageBtn.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                // 확인 다이얼로그 창 생성
                JOptionPane.showConfirmDialog(null, "조심하세요!!!", "메세지버튼", JOptionPane.ERROR_MESSAGE);
            }
        });    
    }
Colored by Color Scripter
cs
 

4. 라디오버튼 계산기 예제

 

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
public class Ex39_Event extends JFrame {
    public Ex39_Event() {
        setTitle("계산기 예제 -3");
        
        JPanel container1 = new JPanel(); //상단
        JPanel container2 = new JPanel(); //상단
        JPanel container3 = new JPanel(); //중단
        JPanel container4 = new JPanel(); //하단
        
        //1.컴포넌트 만들기
        //1-1 상단 컨테이너 컴포넌트1
        JLabel su1 = new JLabel("수 1");
        JTextField su1_box = new JTextField(5);
        JLabel su2 = new JLabel("수 2");
        JTextField su2_box = new JTextField(5);
        
        //1-2 상단 컨테이너 컴포넌트2
        JLabel op = new JLabel("연산자");
        JRadioButton jrb1 = new JRadioButton("+");
        JRadioButton jrb2 = new JRadioButton("-");
        JRadioButton jrb3 = new JRadioButton("*");
        JRadioButton jrb4 = new JRadioButton("/");
        ButtonGroup bg = new ButtonGroup();
        bg.add(jrb1); bg.add(jrb2); bg.add(jrb3); bg.add(jrb4);
        
        //1-3 중앙 컨테이너 컴포넌트
        JTextArea contents = new JTextArea(10, 20);
        JScrollPane jsp = new JScrollPane(contents, 
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        contents.setLineWrap(true);
        
        //1-4 하단 컨테이너 컴포넌트
        JButton result = new JButton("계산");
        JButton exit= new JButton("종료");
        JButton cancel = new JButton("취소");
        
        //2-1 상단 컨테이너 구현
        container1.add(su1); container1.add(su1_box); 
container1.add(su2); container1.add(su2_box);
        container2.add(op); 
        container2.add(jrb1); container2.add(jrb2); container2.add(jrb3); container2.add(jrb4);
        //2-2 중단 컨테이너
        container3.add(jsp);
        //2-3 하단 컨테이너
        container4.add(result); container4.add(exit); container4.add(cancel);
        
        //같은 구역 정렬시 가려지는 현상 해결하기.
        //새 컨테이너 두개 생성.
        //JPanel containerGroup1 = new JPanel(new BorderLayout());
        JPanel containerGroup2 = new JPanel(new BorderLayout());
        
        //새로운 컨테이너에 기존 컨테이너 올리기
        //containerGroup1.add(container1, BorderLayout.NORTH);
        containerGroup2.add(container2, BorderLayout.NORTH); 
        containerGroup2.add(container3, BorderLayout.CENTER); 
        containerGroup2.add(container4, BorderLayout.SOUTH);
        
        
        //3. 프레임 설계
        add(container1, BorderLayout.NORTH);
        add(containerGroup2, BorderLayout.CENTER);
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setBounds(200, 200, 300, 300);
        setVisible(true);
        
        //4. 이벤트 처리
        result.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                int num1 = Integer.parseInt(su1_box.getText());
                int num2 = Integer.parseInt(su2_box.getText());
                
                String result = "";
                if(jrb1.isSelected()) {
                    result = "결과 >>> " + (num1 + num2); 
                }else if(jrb2.isSelected()) {
                    result = "결과 >>> " + (num1 - num2);
                }else if(jrb3.isSelected()) {
                    result = "결과 >>> " + (num1 * num2);
                }else if(jrb4.isSelected()) {
                    result = "결과 >>> " + (num1 / num2);
                }
                
                contents.append(result + "\n");
                su1_box.setText(""); su2_box.setText(""); bg.clearSelection();
            }
        });
        
        //종료 버튼 이벤트 처리
        exit.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
                
            }
        });
        
        //취소 버튼 이벤트 처리
        cancel.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                su1_box.setText(""); su2_box.setText(""); 
                bg.clearSelection(); contents.setText(null);
                su1_box.requestFocus();
                
            }
        });
    }
Colored by Color Scripter
cs

5. 커피 자판기 예제

 

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
public class Ex41_Event extends JFrame {
    public Ex41_Event() {
        
        setTitle("커피 자판기");
        
        //컨테이너 생성.
        JPanel con1 = new JPanel();
        JPanel con2 = new JPanel();
        JPanel con3 = new JPanel();
        JPanel con4 = new JPanel();
        JPanel con5 = new JPanel();
        //컨테이너 그룹화.
        JPanel conGroup1 = new JPanel(new BorderLayout());
        JPanel conGroup2 = new JPanel(new BorderLayout());
        
        conGroup1.add(con1, BorderLayout.NORTH); conGroup1.add(con2, BorderLayout.CENTER);
        conGroup2.add(con3, BorderLayout.NORTH); conGroup2.add(con4, BorderLayout.CENTER); 
conGroup2.add(con5, BorderLayout.SOUTH);
        
        //컴포넌트 생성
        //최상단
        JLabel title = new JLabel("원하는 커피 선택");
        //선택지
        JRadioButton jb1 = new JRadioButton("아메리카노(2500)");
        JRadioButton jb2 = new JRadioButton("카페모카(3500)");
        JRadioButton jb3 = new JRadioButton("에스프레소(2500)");
        JRadioButton jb4 = new JRadioButton("카페라떼(4000)");
        ButtonGroup bg = new ButtonGroup();
        bg.add(jb1); bg.add(jb2); bg.add(jb3); bg.add(jb4);
        //수량, 입금액
        JLabel count = new JLabel("수   량");
        JTextField countBox = new JTextField(10);
        JLabel money = new JLabel("입금액");
        JTextField moneyBox = new JTextField(10);
        //내용박스
        JTextArea contents = new JTextArea(20, 50);
        //최하단 버튼
        JButton b1 = new JButton("계산");
        JButton b2 = new JButton("종료");
        JButton b3 = new JButton("취소");
        
        
        //2. 컨테이너에 컴포들 배치
        con1.add(title);
        con2.add(jb1); con2.add(jb2); con2.add(jb3); con2.add(jb4);
        con3.add(count); con3.add(countBox); con3.add(money); con3.add(moneyBox);
        con4.add(contents);
        con5.add(b1); con5.add(b2); con5.add(b3);
        
        //3.프레임에 배치
        add(conGroup1, BorderLayout.NORTH);
        add(conGroup2, BorderLayout.CENTER);
        setBounds(200, 200, 400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        pack();
        
        //이벤트 처리
        //계산
        b1.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedMenu = "";
                int selectedMenuPrice = 0;
                if(jb1.isSelected()) {
                    selectedMenu = "아메리카노";
                    selectedMenuPrice = 2500;
                }else if(jb2.isSelected()) {
                    selectedMenu = "카페모카";
                    selectedMenuPrice = 3500;                            
                }else if(jb3.isSelected()) {
                    selectedMenu = "에스프레소";
                    selectedMenuPrice = 2500;
                }else if(jb4.isSelected()) {
                    selectedMenu = "카페라떼";
                    selectedMenuPrice = 4000;
                }
                int providePrice = selectedMenuPrice*Integer.parseInt(countBox.getText());
                int vat = (int)(providePrice*0.1);
                int inputMoney = Integer.parseInt(moneyBox.getText());
                
                contents.append("커피종류: " + selectedMenu + "\n" 
                +"커피단가: " + selectedMenuPrice + "원\n"
                +"수량: " + countBox.getText() + "\n"
                +"공급가액: " + providePrice + "원\n"
                +"부가세액: " + vat + "원\n"
                +"총금액: " + (providePrice + vat) + "원\n"
                +"입금액: " + inputMoney + "원\n"
                +"거스름돈: " + (inputMoney - providePrice - vat) + "원\n"
                );                
            }
        });        
        //종료
        b2.addActionListener(new ActionListener() {            
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);                
            }
        });        
        //취소
        b3.addActionListener(new ActionListener() {            
            @Override
            public void actionPerformed(ActionEvent e) {
                bg.clearSelection(); contents.setText(null);
                countBox.setText(""); moneyBox.setText("");                
            }
        });
    }
Colored by Color Scripter
cs

6. 글자색 바꾸기(컬러 다이얼로그 이용)

 

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
public class Ex42_Event extends JFrame {
    
    public Ex42_Event() {
        setTitle("색상 예제");
        JMenuBar bar = new JMenuBar();
        JMenu menu = new JMenu("글자");
        JMenuItem item = new JMenuItem("글자색");
        
        //메뉴에 메뉴아이템을 추가해 줘야 함.
        menu.add(item);
        
        //메뉴바에 메뉴를 올려 줘야 함.
        bar.add(menu);
        
        setJMenuBar(bar);
        
        JPanel container = new JPanel(new BorderLayout());
        
        //1.컴포 생성
        JLabel label = new JLabel("방가방가");
        label.setFont(new Font("맑은 고딕", Font.ITALIC, 25));
        
        //**중앙 정렬
        label.setHorizontalAlignment(SwingConstants.CENTER);
        
        //2.컨테이너에 컴포 넣기
        container.add(label);
        
        //3.프레임에 컨테이너 넣기
        add(container, BorderLayout.CENTER);
        setBounds(200, 200, 300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        
        //4.이벤트 처리
        //"글자색" 메뉴 선택시 이벤트
        item.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                // 이벤트를 발생시킨 객체(컴포넌트)의 문자열을 가져오는 메서드
                String command = e.getActionCommand();
                if(command.equals("글자색")) {
                    //컬러 다이얼로그 출력 후 사용자가 선택한 색상을 받아오는 작업.
                    Color selectedColor = JColorChooser.showDialog(null, "color", Color.BLACK);
                    if(selectedColor != null) {
                        label.setForeground(selectedColor);
                    }
                }
                
            }
        });    
    }
Colored by Color Scripter
cs

'국기훈련과정 > JAVA 복습노트' 카테고리의 다른 글

01. JAVA의 시작.  (0) 2021.09.01
13. GUI_다중 화면 예제  (0) 2021.09.01
13. GUI_Event  (0) 2021.08.27
13. GUI_03  (0) 2021.08.26
13. GUI_02  (0) 2021.08.26
'국기훈련과정/JAVA 복습노트' 카테고리의 다른 글
  • 01. JAVA의 시작.
  • 13. GUI_다중 화면 예제
  • 13. GUI_Event
  • 13. GUI_03
Purewater
Purewater
Purewater
프로그램 공부 일기장
Purewater
전체
오늘
어제
  • 분류 전체보기 (237)
    • Front-end (8)
      • Vue (8)
    • 포트폴리오 (3)
      • JSP SHOP (1)
      • Travelanner (1)
      • OAuth2 Blog (1)
    • 취업 준비 (70)
      • Spring boot (43)
      • JPA (1)
      • Spring security (14)
      • React (11)
      • 면접 기록 (1)
    • 국기훈련과정 (57)
      • JAVA 복습노트 (12)
      • Oracle SQL (9)
      • Web (15)
      • JSP (6)
      • Spring (10)
      • 프로젝트 (4)
      • Python (1)
    • 알고리즘 문제풀이 (17)
      • Python3 (13)
      • Kotlin (4)
    • 이것저것 지식 (9)
    • 클라우드 서버 (7)
      • Linux (7)
    • Backend (20)
      • node.js (9)
      • JAVA (6)
      • spring boot (5)
    • DB (1)
      • SQL (1)
    • 잡담 (1)
    • 강의 수강 (1)
    • CS 지식 (41)
      • 디자인패턴 (6)
      • 네트워크 (22)
      • 데이터베이스 (4)

블로그 메뉴

  • 대문
  • 태그
  • 방명록
  • 글쓰기

공지사항

인기 글

태그

  • Postman
  • Java
  • Kotlin
  • GUI
  • PostgreSQL
  • redis
  • spring
  • gitignore
  • JPA
  • 노드
  • 디자인패턴
  • node
  • 오라클
  • Oracle
  • js
  • node.js
  • SQL
  • git
  • db
  • 자바스크립트

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
Purewater
13. GUI_Event 예제
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.