JavaFX ButtonJavaFX 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 graphTo 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: Setting the Text of the ButtonThere are two ways of setting the text on the button.
Wrapping Button TextWe 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 buttonButton 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: 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: Button ActionButton 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: Button EffectsWe 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: Next TopicJavaFX RadioButton |