2019.01.15 JavaFX에서 키보드 동작(액션)

2019. 1. 15. 17:20JAVA

<키보드 액션 이벤트>


#1 MainAPP

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
package com.exam.app;
/* 키보드 액션 이벤트 */
 
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
 
public class MainApp extends Application {
 
    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("view/Root.fxml"));
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.setTitle("키보드 이벤트");
        primaryStage.setResizable(false); // 창크기 고정
        primaryStage.show();
    }
 
    public static void main(String[] args) {
        launch(args);
    }
}
 
cs



#2 Root.fxml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
 
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
 
<AnchorPane prefHeight="300.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.exam.app.view.RootController">
   <children>
      <TextField fx:id="tf1" layoutX="26.0" layoutY="33.0" promptText="keyPressed" />
      <TextField fx:id="tf3" layoutX="26.0" layoutY="111.0" promptText="keyExpress" />
      <TextField fx:id="tf2" layoutX="26.0" layoutY="72.0" promptText="keyTyped" />
      <Label fx:id="label1" layoutX="177.0" layoutY="72.0" prefHeight="23.0" prefWidth="62.0" text="0/10">
         <font>
            <Font size="17.0" />
         </font>
      </Label>
      <Button fx:id="btnGo2" layoutX="325.0" layoutY="22.0" mnemonicParsing="false" text="Next" />
   </children>
</AnchorPane>
 
cs



#3 RootController.java

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
package com.exam.app.view;
 
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
 
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
 
public class RootController implements Initializable {
    @FXML
    private TextField tf1, tf2, tf3;
    @FXML
    private Label label1;
    @FXML
    private String str;
    @FXML
    private Button btnGo2;
    
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        /*화면 이동*/
        btnGo2.setOnAction(event->{
            try {
                handleBtnGo2(event);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });//btnGo2()
        
        /**/
        tf1.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                System.out.println("[KeyPressed]");
                System.out.println("tf1.KeyCode: " + event.getCode());
                System.out.println("tf1.Text: " + event.getText());
                System.out.println("tf1.Character: " + event.getCharacter());
                }
        });// tf1()
        
        /**/
        tf2.setOnKeyTyped(new EventHandler<KeyEvent>() { 
            // 문자키를 입력할 때 이벤트 처리, 문자키만 입력받음
            // 기능키 입력 X
            @Override
            public void handle(KeyEvent event) {
                System.out.println("[keyTyped]");
                System.out.println("tf2.KeyCode: " + event.getCode());
                System.out.println("tf2.Text: " + event.getText());
                System.out.println("tf2.Character: " + event.getCharacter());
                
 
            }
        });// tf2.setOnKeyTyped()
 
        /**/
        tf3.setOnKeyReleased(event -> { //키를 누르고 땔 때 동작
            System.out.println("[keyReleased]");
            System.out.println("tf3.KeyCode: " + event.getCode());
            System.out.println("tf3.Text: " + event.getText());
            System.out.println("tf3.Character: " + event.getCharacter());
        });
        
        /*입력된 문자 개수 카운트*/
        tf2.setOnKeyReleased(new EventHandler<KeyEvent>() { 
            @Override
            public void handle(KeyEvent event) {
                System.out.println(event.getText());
                int count =tf2.getText().length();
                label1.setText(count+"/10");
                if(count>10) {
                    label1.setStyle("-fx-text-fill:red;");
                }else {
                    label1.setStyle("-fx-text-fill:black;");
                }
            }
            
        });//tf2.count
        
        
    } // initialize()
    
    /* 화면이동 메소드*/
    public void handleBtnGo2(ActionEvent event) throws IOException {
        Parent second = FXMLLoader.load(getClass().getResource("Root2.fxml"));
        Scene scene = new Scene(second);
        Stage primaryStage =(Stage)btnGo2.getScene().getWindow();    
        primaryStage.setScene(scene);
    }//handBtnGo2
 
}
 
cs



#4 Root2.fxml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
 
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
 
 
<AnchorPane prefHeight="300.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.exam.app.view.RootController2">
   <children>
      <ImageView fx:id="mario" fitHeight="105.0" fitWidth="73.0" focusTraversable="true" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@mario.png" />
         </image>
      </ImageView>
   </children>
</AnchorPane>
 
cs



#5 RootController2.java

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
package com.exam.app.view;
 
/*키보드 방향키에 따라 이미지 움직이게 하기*/
import java.net.URL;
import java.util.ResourceBundle;
 
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
 
public class RootController2 implements Initializable {
    @FXML
    private ImageView mario;
 
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        /* 키보드 입력에 따라 이미지 위치 변경 */
        mario.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                handleImage(event);
            }
        });// mario
 
    }// initialize()
 
    /* 이미지 위치변경 메소드 */
    public void handleImage(KeyEvent event) {
        KeyCode keyCode = event.getCode();
        if (keyCode.equals(KeyCode.RIGHT)) {
            mario.setX(mario.getX() + 10);
        } else if (keyCode.equals(KeyCode.LEFT)) {
            mario.setX(mario.getX() - 10);
        } else if (keyCode.equals(KeyCode.UP)) {
            mario.setY(mario.getY() - 10);
        } else if (keyCode.equals(KeyCode.DOWN)) {
            mario.setY(mario.getY() + 10); // GET으로 Y좌표값을 받은다음, SET으로 Y좌표에 대입
        }
    }//handleImage()
}
 
cs




▼ 출력 화면  



** 이미지에 마우스 포인터가 클릭되었을때 동작되기 하기 위해 SceneBuilder에서 조작

-> Focus Traversable를 체크 !






'JAVA' 카테고리의 다른 글

2019.01.21 배치처리  (0) 2019.01.22
2019.01.18 파일 읽어오기  (0) 2019.01.18
2019.01.14 JavaFx 활용하기  (0) 2019.01.14
2018.01.11 멀티 스레드의 활용  (0) 2019.01.11
2019.01.09 스레드 Thread, 예외처리  (0) 2019.01.09