【问题标题】:Add image to a button at a specific position JavaFX将图像添加到特定位置的按钮JavaFX
【发布时间】:2012-09-22 14:13:33
【问题描述】:

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

【问题讨论】:

    标签: image button javafx


    【解决方案1】:

    在按钮上设置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
    

    【讨论】:

    • 是的,所有带标签的项目(例如按钮)都有-fx-content-display css 属性。参考CSS reference guide for Labeled
    • 谢谢。这个伪 CSS 的官方文档是一团糟,我自己找不到合适的属性(首先我必须知道在哪里看)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2017-04-07
    相关资源
    最近更新 更多