JavaFX:如何制作一个带有两(2)个或更多图标的按钮?

Pie*_*nry 1 java user-interface javafx

有很多关于如何将图形添加到JavaFX按钮的在线资源.

但是我想知道是否有办法添加第二个(或任何数字,但在大多数情况下可能没有多大意义的2个以上的图像)图像.

我的用例:我有一个左边有方形图标的按钮,后面是文字标签.图像是按钮与之链接的一些现实生活概念的表示(例如汽车或人).我想在一些按钮的右边添加一个小图标,一个"右V形符号"来表示交互的性质.

在此输入图像描述

我想也许可以使用全宽度的HBox作为按钮的图形节点,并将2个图像添加到它,但我不认为可以将文本放在图形节点的顶部.

任何的想法 ?

Rol*_*and 6

使用图标和文本创建自己的自定义节点并将其设置为图形.当然,您不显示按钮文本,因为它已经在您的自定义图形节点中.

这是一个简单的例子.您需要提供文件icon1.png和icon2.png.

public class ButtonWithMultipleIcons extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {

            Group group = new Group();

            Button button = new Button();
            button.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);

            HBox hBox = new HBox();

            ImageView icon1 = new ImageView( getClass().getResource( "icon1.png").toExternalForm());
            ImageView icon2 = new ImageView( getClass().getResource( "icon2.png").toExternalForm());

            Label label = new Label("Text");

            //make the button grow if you want the right icon to always be on the right of the button :
            label.setMaxWidth(Long.MAX_VALUE);

            HBox.setHgrow(label, Priority.ALWAYS);


            hBox.getChildren().addAll( icon1, label, icon2);

            button.setGraphic(hBox);

            group.getChildren().add( button);

            Scene scene = new Scene(group,400,400);
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Run Code Online (Sandbox Code Playgroud)