zoukankan      html  css  js  c++  java
  • JavaFX——添加事件

    最简单的例子:点击按钮在控制台打印文字。

    在Java代码中,要给按钮添加事件,只需要调用其 setOnAction 方法,并指定事件发生时的操作即可。

    package sample;
    
    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.StackPane;
    import javafx.scene.text.Font;
    import javafx.stage.Stage;
    
    public class Main extends Application {
    
        @Override
        public void start(Stage primaryStage) throws Exception{
            StackPane root = new StackPane();
            Scene scene = new Scene(root, 400, 300);
    
            primaryStage.setTitle("JavaFX 学习");
            primaryStage.setScene(scene);
            primaryStage.show();
    
            Button button = new Button("快点我");
            button.setStyle("-fx-background-color: #ff9999; -fx-padding: 10px 20px;");
            button.setFont(new Font(16));
            button.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    System.out.println("哎呀,讨厌!");
                }
            });
    root.getChildren().add(button); }
    public static void main(String[] args) { launch(args); } }

    setOnAction 方法接收的 EventHandler 是一个函数式接口,可用 lambda 表达式替换:

    button.setOnAction(event -> System.out.println("哎呀,讨厌!"));

    示例如下图:


    The End.

  • 相关阅读:
    leetcode 33. Search in Rotated Sorted Array
    leetcode 28. Implement strStr()
    Scala函数
    布隆过滤器相关知识
    Storm 流式计算框架
    java高并发核心类 AQS(Abstract Queued Synchronizer)抽象队列同步器
    操作系统类型&操作系统结构&现代操作系统基本特征
    Kafka笔记
    Redis shell
    Lucene笔记
  • 原文地址:https://www.cnblogs.com/weix-l/p/13789433.html
Copyright © 2011-2022 走看看