I wanted to do a more cumbersome way, but I will not. I will try to write a way through css .
Note: in general, when working with styles and css usually all styles are written in a separate file, and then this file is connected with styles and works directly with selectors. Like that:
Scene scene = new Scene(root, 300, 250); scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show();
Suppose you have a cross and a picture and this picture with the class is in the same folder (although of course it is better to put it in a separate folder with resources)
Therefore, the string with its path will be valid
String declineImage = getClass().getResource("decline.png").toExternalForm();
At the button we set the styles:
btn.setStyle("-fx-background-image: url('" + image + "'); -fx-background-repeat: no-repeat; -fx-background-position: 8px 4px;");
where we specify the picture in the background, position, etc. This is a regular css
And at the OnMouseEnter / OnMouseExit mouse event, we make a rectangle transparent:
btn.setOnMouseEntered(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { new Timeline( new KeyFrame(Duration.seconds(0), new KeyValue(rc.opacityProperty(), 1)), new KeyFrame(Duration.seconds(0.5), new KeyValue(rc.opacityProperty(), 0)) ).play(); } }); btn.setOnMouseExited(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { new Timeline( new KeyFrame(Duration.seconds(0), new KeyValue(rc.opacityProperty(), 0)), new KeyFrame(Duration.seconds(0.5), new KeyValue(rc.opacityProperty(), 1)) ).play(); } });
The way to install the image in the background is not via css :
// new Image(url) Image image = new Image(CurrentClass.class.getResource("/path/to/package/bg.jpg")); // new BackgroundSize(width, height, widthAsPercentage, heightAsPercentage, contain, cover) BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, false); // new BackgroundImage(image, repeatX, repeatY, position, size) BackgroundImage backgroundImage = new BackgroundImage(image, BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize); // new Background(images...) Background background = new Background(backgroundImage);
You can adapt it for yourself.