VeeAyeInIn
VeeAyeInIn

Reputation: 193

JavaFX how to "crop" graphics to buttons

Essentially, what I want is to create a Button with a cropped graphic. Cropped in the sense of, the Image is in the back, and the Button is a hole, showing the Graphic. As of now, it looks likeFailed Attempt

However I want the graphic to fit the button, even if its bigger, to just get cut off. My current code is along the lines of

Image image = new Image(Main.class.getResource("/texture.png").toExternalForm());
yesButton.setGraphic(new ImageView(image));

Upvotes: 0

Views: 318

Answers (1)

dzikoysk
dzikoysk

Reputation: 1578

You can set a background using javafx css:

Button button = new Button("Button");
button.setStyle("-fx-background-image: url('/texture.png')");

Or programmatically with Background by setBackground:

Image image = new Image(Main.class.getResource("/texture.png").toExternalForm());
BackgroundImage backgroundImage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT,
        BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.AUTO);
Background background = new Background(backgroundImage);

Button button = new Button("Button");
button.setBackground(background);

Upvotes: 4

Related Questions