JavaFX UI Controls – Button use in JavaFX Application

In this tutorial session, we will learn the following things about JavaFX UI control – Button.

We are going to discuss on following points in detail, also we will learn how to write code for this.
1) How to set the icon image on the button?
2) Handling button click action? (with lambda expression and traditional FXML way)
3) Applying effects on the button.
     -Adding the shadow when the mouse cursor is on
     -Removing the shadow when the mouse cursor is off
4) Styling button with CSS.

Let’s start with the first action item.
1) How to set the image icon on the button? 
    To set the image icon on the button, first, we need to create an Image Class object with help of the given image reading as a resource stream then use the ImageView object to convert this image object as a node then passes in setGraphic() method as a parameter. Please check the below lines of code.

Image image = new Image(getClass().getResourceAsStream(“likeImage.png”));
button1.setGraphic(new ImageView(image));


2) Handling button click action when not using FXML.
    In this case, we need to use the following code to handle the button click action.
   button.setOnAction( (ActionEvent event) -> {
   //do some action
   label2.setText( “Hello Cool IT Help!” );
   });
    
      In case we are using FXML then we need to handle click events in another way. First, we need to create a method by using @FXML annotation then open FXML file with scene builder and then go under inspector –>code section then set select this method name from OnAction dropdown. Please see the below image.

I have explained all these things in my video tutorial posted on YouTube. Please click to watch the below video for a better understanding of each concept.
3) Applying effects on the button.

     -Adding the shadow when the mouse cursor is on
     -Removing the shadow when the mouse cursor is off

Here we are going to apply a drop shadow effect on the button. To do that we need to use the following code and this is very straightforward and easy. Please check the below code snippet.

DropShadow shadow = new DropShadow();
//Adding the shadow when the mouse cursor is on
button2.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
button2.setEffect(shadow);
});

//Removing the shadow when the mouse cursor is off
button2.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
button2.setEffect(null);
});


4) Styling button with CSS.

    To apply styling on a button or any other JavaFX control we need to take the help of CSS. Here we will create a CSS file and then applying on the scene with the following line of code.
 scene.getStylesheets().add(“CSS/newCascadeStyleSheet.css”);

For complete clarification and a detailed understanding of points 3 and point please watch my Video Tutorial session that I have posted on YouTube. Please click to watch the below video for a better understanding of each concept.

 

Leave a Comment