javafx 图片作按钮_添加图片到一个按钮在特定位置的JavaFX

在JavaFX中,默认情况下,按钮上的图片和文本会水平排列。要改变这种行为,使文本位于图片下方,可以使用button.setContentDisplay(ContentDisplay.TOP)。示例代码展示了一个包含图片和文本的按钮,当点击时,会显示响应文本。
摘要由CSDN通过智能技术生成

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 ?

解决方案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() {

@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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值