How to add an image to a button (action) in 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.

Adding image to a button

You can add a graphic object (node) to a button using the setGraphic() method of the Button class (inherited from javafx.scene.control.Labeled class). This method accepts an object of the Node class representing a graphic (icon).

To add an image to a button −

  • Create an Image object bypassing the path for the required graphic.

  • Create an ImageView object using the image object.

  • Create a button by instantiating the Button class.

  • Finally, invoke the setGraphic() method on the button by passing the ImageView object as a parameter.


import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ButtonGraphis extends Application {
   public void start(Stage stage) {
      //Creating a graphic (image)
      Image img = new Image("UIControls/logo.png");
      ImageView view = new ImageView(img);
      //Creating a Button
      Button button = new Button();
      //Setting the location of the button
      //Setting the size of the button
      button.setPrefSize(80, 80);
      //Setting a graphic to the button
      //Setting the stage
      Group root = new Group(button);
      Scene scene = new Scene(root, 595, 170, Color.BEIGE);
      stage.setTitle("Button Graphics");
   public static void main(String args[]){