Add image to a button at a specific position JavaFX


Question

When I add image and text to a button, by default elements are set horizontally. How can I change this behavior to get text under image ?

1
14
10/1/2012 5:38:46 PM

Accepted Answer

Set the contentDisplayProperty on the button.

button.setContentDisplay(ContentDisplay.TOP);

Here is an executable example:

import javafx.application.Application;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ButtonGraphicTest extends Application {
  @Override public void start(final Stage stage) throws Exception {
    final Label response = new Label();
    final ImageView imageView = new ImageView(
      new Image("http://icons.iconarchive.com/icons/eponas-deeway/colobrush/128/heart-2-icon.png")
    );
    final Button button = new Button("I love you", imageView);
    button.setStyle("-fx-base: coral;");
    button.setContentDisplay(ContentDisplay.TOP);
    button.setOnAction(new EventHandler<ActionEvent>() {
      @Override public void handle(ActionEvent event) {
        response.setText("I love you too!");
      }
    });

    final VBox layout = new VBox(10);
    layout.setAlignment(Pos.CENTER);
    layout.getChildren().addAll(button, response);
    layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10; -fx-font-size: 20;");
    stage.setScene(new Scene(layout));
    stage.show();
  }
  public static void main(String[] args) { launch(args); }
}
// icon license: (creative commons with attribution) http://creativecommons.org/licenses/by-nc-nd/3.0/
// icon artist attribution page: (eponas-deeway) http://eponas-deeway.deviantart.com/gallery/#/d1s7uih

Sample program output

24
10/1/2012 9:57:16 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon