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

标签 image button javafx

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

最佳答案

设置 contentDisplayProperty在按钮上。

button.setContentDisplay(ContentDisplay.TOP);

这是一个可执行示例:
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

关于image - 将图像添加到特定位置的按钮 JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12678197/

相关文章:

java - 抽象类和子类中的静态变量初始化

android - 如何在java canvas中启用android抗锯齿功能?

html - 如何使用 flexbox 在中心底部对齐元素

javafx - Smack 名单条目为空

java - Platform.runLater 问题 - 延迟执行

c# - byte[] 的图像无限期挂起

css - 让图像与 div 重叠并位于文本后面

javascript - 获取所选单选按钮的组合以在单击按钮时显示消息

swift - Ui 按钮未添加到 SkScene

JavaFX TableView ScrollBar 值说明