将图像添加到JavaFX特定位置的按钮

Adi*_*dil 15 javafx image button

当我将图像和文本添加到按钮时,默认情况下元素是水平设置的.如何更改此行为以获取图像下的文本?

jew*_*sea 26

在按钮上设置contentDisplayProperty.

button.setContentDisplay(ContentDisplay.TOP);
Run Code Online (Sandbox Code Playgroud)

这是一个可执行的例子:

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
Run Code Online (Sandbox Code Playgroud)

示例程序输出

  • 是的,所有标记的项目(如按钮)都具有`-fx-content-display` css属性.请参阅[标签的CSS参考指南](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#labeled). (2认同)