Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add image to a button at a specific position JavaFX

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 ?

like image 384
Adil Avatar asked Oct 01 '12 17:10

Adil


1 Answers

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

like image 114
jewelsea Avatar answered Oct 14 '22 17:10

jewelsea