- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement JavaFX event handling using lambda in Java?
JavaFX Button class provides the setOnAction() method that can be used to set an action for the button click event. An EventHandler is a functional interface and holds only one method is the handle() method.
Syntax
@FunctionalInterface public interface EventHandler<T extends Event> extends EventListener
In the below example, we can able to implement event handling of JavaFX by using a lambda expression.
Example
import javafx.application.*; import javafx.beans.property.*; import javafx.event.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; public class LambdaWithJavaFxTest extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) throws Exception { BorderPane root = new BorderPane(); ToggleButton button = new ToggleButton("Click"); final StringProperty btnText = button.textProperty(); button.setOnAction((event) -> { // lambda expression ToggleButton source = (ToggleButton) event.getSource(); if(source.isSelected()) { btnText.set("Clicked!"); } else { btnText.set("Click!"); } }); root.setCenter(button); Scene scene = new Scene(root); stage.setScene(scene); stage.setWidth(300); stage.setHeight(250); stage.show(); } }
Output
Advertisements
To Continue Learning Please Login
Login with Google