JavaFX 按钮背景图片 [英] JavaFX button background image

查看:135
本文介绍了JavaFX 按钮背景图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JavaFX 中的按钮上设置 backgroundImage 时遇到问题.

I have problem with setting backgroundImage on button in JavaFX.

Image newGame = new Image("File:/CSS/nova_hra.png");
BackgroundImage newGameBgr = new BackgroundImage(newGame, null, null, null, null);

Button buttonNewGame = new Button("Nová Hra");
Button buttonLoadGame = new Button("Načíst Hru");
Button buttonStatistics = new Button("Statistiky");
Button buttonExit = new Button("Konec");

buttonNewGame.setGraphic(new ImageView(newGame));
//buttonNewGame.setBackground(new Background(newGameBgr));

buttonExit.setMinHeight(40);
buttonLoadGame.setMinHeight(40);
buttonNewGame.setMinHeight(40);
buttonStatistics.setMinHeight(40);

buttonExit.setMinWidth(120);
buttonLoadGame.setMinWidth(120);
buttonNewGame.setMinWidth(120);
buttonStatistics.setMinWidth(120);

这对 buttonNewGame 没有任何作用.每次我尝试用这个加载图像时

This does nothing with the buttonNewGame. Every time I tryed to load image with this

Image image = new Image(getClass().getResourceAsStream("a.png"));

我得到了运行时异常.当我使用

I got runTime exception. When I used

Image image = new Image(getClass().getResourceAsStream("a.png"));

整个图像消失了.

推荐答案

你可以通过 css 来实现.如果您的 background.jpg 在测试包中,只需执行以下操作:

You can do it via css. If your background.jpg is in a package testing, simply do this:

    package testing;

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.Pane;
    import javafx.stage.Stage;

    public class Main extends Application {

        @Override
        public void start(Stage primaryStage) {

            try {

                Pane root = new Pane();

                Button button = new Button( "Click me!");
                button.setStyle("-fx-background-image: url('/testing/background.jpg')");

                root.getChildren().add(button);

                Scene scene = new Scene(root, 800, 400);
                primaryStage.setScene(scene);
                primaryStage.show();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static void main(String[] args) {
            launch(args);
        }
    }

如果你不想使用 css,你可以这样做:

If you don't want to use css, you could do it like this:

        BackgroundImage backgroundImage = new BackgroundImage( new Image( getClass().getResource("/testing/background.jpg").toExternalForm()), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT);
        Background background = new Background(backgroundImage);

        Button button = new Button( "Click me!");
        button.setBackground(background);

这篇关于JavaFX 按钮背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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