Creating Buttons

In this section, we will demonstrate how to create simple buttons using JavaFX. After reading the section, you will know how to create a simple button and handling the events. Lets see a basic example on how to make a button appear on the window.

Example



Click here to download the example

The above example is pretty self explanatory. We import the scene layout, then using the HBox layout we are able to create buttons and place the buttons horizontally. We will see some more examples on HBox layout and VBox layout. The difference between the HBox and VBox layout, one organize the buttons horizontally and the other one organize the button vertically. It's easy to tell that HBox organize the buttons horizontally and VBox organize the buttons vertically. Now lets observe an example using HBox layout that organize three buttons.


Example


 


Click here to download the example

 

The above example is very similar to the previous example. In this example, we specify the space between the buttons by assigning a value to the space. Now to create three buttons, we would create it one by one then separate the buttons by a comma.

 

Handling Button Events

We just learn how to create buttons, now lets observer how we are going to handle button events if the user clicks a button. The following example will create three buttons Red, Green, and Blue. A click on any of the buttons change the window background color.

 

Example


Click here to download the example

 To wrap up the button section, we will see another example on how to handle button events. In the following example, we will try to change the color of the text by a click of a button.

 

Example


Click here to download the example

 

This concludes our button section. Notice for both of the examples we used the keyword " bind ." If we didn't use the keyword bind, a click of the button will not update the text or the background, hence the text color or the background color will not be change.


 

  <JavaFX><Home>