Button and Event Handlers

The first and most common control is button's family. Button has an EventHandler that is called when Button is clicked (or fired). All code in the event handler is always run on JavaFX Application Thread:

// chapter2/other/ButtonDemo.javaButton btn = new Button();btn.setText("Say 'Hello World'");btn.setOnAction(new EventHandler<ActionEvent>() {    @Override    public void handle(ActionEvent event) {        System.out.println("Hello World!");    }});

In addition to text, you can use any Node inside a button:

Button btn = new Button();btn.setText("Say 'Hello World'");btn.setGraphic(new Circle(10));

Button can be assigned the roles of default button or cancel button, responding to Enter or Esc correspondingly:

btn.setDefaultButton(true); ...

Get Mastering JavaFX 10 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.