JavaFX Button

JavaFX button control is represented by javafx.scene.control.Button class. A button is a component that can control the behaviour of the Application. An event is generated whenever the button gets clicked.

How to create a Button?

Button can be created by instantiating Button class. Use the following line to create button object.

Adding a Button to the scene graph

To visualize the button on the screen, we must attach it to the scene object. The following code creates a button and adds it to the scene object.

Output:


JavaFX Button

Setting the Text of the Button

There are two ways of setting the text on the button.

  1. Passing the text into the class constructor
  2. By calling setText("text") method

Wrapping Button Text

We can wrap the text of the button into multiple lines if the text to be displayed is too long. This can be done by calling a setter method setWrapText(boolean) on the instance of Button class. Pass the boolean value true in the method wherever required.

Setting the image on the button

Button class contains a constructor which can accept graphics along with the text displayed on the button. The following code implements image on the button.

Output:


JavaFX Button 1

Using setGraphic() method:

Button class also provides an instance method named setGraphic(). We have to pass the image view object in this method. The following code implements setGraphic() method.

Output:


JavaFX Button 2

Button Action

Button class provides setOnAction() methodwhich is used to set the action for the button click event. An object of the anonymous class implementing the handle() method, is passed in this method as a parameter.

We can also pass lambda expressions to handle the events. The following code implements the Button event.

Output:


JavaFX Button 3

Button Effects

We can apply the effects to a Button. The effects are provided by javafx.scene.effect package. The following code shows how the drop shadow effect can be applied to a button.

Output:


JavaFX Button 4
Next TopicJavaFX RadioButton




Contact US

Email:[email protected]

JavaFX Button
10/30