Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the types of buttons provided by JavaFX?
A button controls in user interface applications, in general, on clicking the button it performs the respective action.
You can create a Button by instantiating the javafx.scene.control.Button class. Using this class, you can create three kinds of buttons. They are −
Normal − A regular button that triggers respective action (if any) when pressed.
Default − In case of in focus this button is triggered when the Enter button is pressed. You can set a button as the default button bypassing “true” as a value to the setDefaultButton() method.
Cancel −In case of in focus this button is triggered when the Esc button is pressed. You can set a button as cancel button bypassing “true” as a value to the setCancelButton() method.
Example
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ButtonTypes extends Application {
@Override
public void start(Stage stage) {
//Creating a Button
Button defaultBtn = new Button();
defaultBtn.setFocusTraversable(true);
defaultBtn.setText("Default (Enter)");
defaultBtn.setTranslateX(150);
defaultBtn.setTranslateY(65);
//Setting as default button
defaultBtn.setDefaultButton(true);
//Adding action listener
defaultBtn.setOnAction(e -> {
System.out.println("Default Button Clicked.");
});
Button cancel = new Button();
//Setting properties
cancel.setFocusTraversable(true);
cancel.setText("Cancel (Esc)");
cancel.setTranslateX(300);
cancel.setTranslateY(65);
//Setting the cancel button
cancel.setCancelButton(true);
//Adding action listener
cancel.setOnAction(e -> {
System.out.println("Cancel Button Clicked.");
});
Button btn = new Button();
btn.setText("Sample");
btn.setTranslateX(450);
btn.setTranslateY(65);
//Adding action listener
btn.setOnAction(e -> {
System.out.println("sample Button Clicked.");
});
//Setting the stage
Group root = new Group(defaultBtn, cancel, btn);
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Button Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Output
On pressing enter the Default button will be triggered and, on pressing escape the Cancel button will be triggered.
