JavaFX:如何制作带有两(2)个或更多图标的按钮? [英] JavaFX : how to make a button with two (2) or more icons?

查看:184
本文介绍了JavaFX:如何制作带有两(2)个或更多图标的按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There is plenty of online resource on how to add a graphic to a JavaFX button.

但是我想知道是否有一种方法可以添加第二个(或任意数量,但是在大多数情况下,多于2个图像可能没有多大意义).

However I would like to know if there is a way to add a second (or any number, but more than 2 images probably woudn't make much sense in most situations) image.

我的用例:我有一个按钮,左边带有方形图标,后跟一个文本标签.该图像表示按钮与之链接的某些现实概念的表示(例如汽车或人).我想在一些按钮的右边添加一个小图标,一个右V形"以指示交互的性质.

My use case : i have a button with a square icon on the left, followed by a text label. The image is a representation of some real-life concept that button is linked with (could e.g. a car or a person). I would like to add a small icon to the right of some buttons, a "right chevron" to indicate the nature of the interaction.

我当时正在考虑使用具有完整宽度的HBox作为按钮的图形节点,并向其中添加2张图像,但是我认为不可能将文本放在图形节点的顶部

I was thinking maybe to use a HBox with the full width as the graphic node of the button, and add the 2 images to it, but I don't think it is possible to put the text on top of the graphic node.

有什么主意吗?

推荐答案

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

Create your own custom node with icons and text and set it as graphic. Of course you don't show the button text because it's already in your custom graphic node.

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

Here's a simple example. You need to provide the files icon1.png and 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);
    }
}

这篇关于JavaFX:如何制作带有两(2)个或更多图标的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆