JavaFx:10、双击事件和检测键盘按键

package fx.com;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;


public class Main extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        Button b2 = new Button();
        b2.setText("这是按钮");
        b2.setLayoutX(100);
        b2.setLayoutY(300);
        b2.setPrefWidth(500);
        b2.setPrefHeight(200);

        b2.setStyle(
                "-fx-background-color: cadetblue;" +
                        "-fx-background-radius: 20;" +
                        "-fx-text-fill: antiquewhite;" +
                        "-fx-font-family: 'Microsoft YaHei UI';" +
                        "-fx-font-size: 50"
        );

        // 按钮单击事件
        b2.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                Button button = (Button) event.getSource();
                System.out.println(button.getText());
            }
        });

        // 响应鼠标的另一种形式
        b2.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            System.out.println(event.getButton().name());

            //System.out.println("鼠标单击");

            if (event.getClickCount() == 2 && event.getButton().name().equals(MouseButton.PRIMARY.name())) {
                System.out.println("鼠标双击");
            }
        });

        // 相应键盘按键按下
        b2.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if (event.getCode().getName().equals(KeyCode.A.getName()))
                System.out.println(event.getCode().getName());
            }
        });

        // 响应键盘按键弹起
        b2.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                System.out.println(event.getCode().getName());
            }
        });

        Group group = new Group();
        group.getChildren().addAll(b2);


        Scene scene = new Scene(group);
        primaryStage.setScene(scene);
        primaryStage.setHeight(600);
        primaryStage.setWidth(800);
        primaryStage.show();
        primaryStage.centerOnScreen();
    }
}
posted @ 2020-10-01 12:41  xl4ng  阅读(1111)  评论(0编辑  收藏  举报