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 ?
Asked
Active
Viewed 3.2k times
1 Answers
29
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

jewelsea
- 150,031
- 14
- 366
- 406
-
2Yes, all labeled items such as buttons have a `-fx-content-display` css attribute. Refer to the [CSS reference guide for Labeled](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#labeled). – jewelsea Oct 18 '16 at 17:43
-
Thanks. The official documentation for this pseudo-CSS is a mess, I couldn't find the proper attribute myself (first I would have to know where to look). – BarbaraKwarc Oct 18 '16 at 18:00