JavaFX按钮背景图像

Dav*_*šta 1 background javafx image button

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

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);
Run Code Online (Sandbox Code Playgroud)

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

Image image = new Image(getClass().getResourceAsStream("a.png"));
Run Code Online (Sandbox Code Playgroud)

我得到了runTime异常.我用的时候

Image image = new Image(getClass().getResourceAsStream("a.png"));
Run Code Online (Sandbox Code Playgroud)

整个形象不顾一切.

Rol*_*and 7

你可以通过CSS来做到这一点.如果你的background.jpg在包测试中,只需执行以下操作:

    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

        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);
Run Code Online (Sandbox Code Playgroud)