2

I'm wondering if there is a way to apply some transformations (i.e. rotate) to an image setted to some button. I am using css to specify all images by such way:

.custom-button {
   -fx-graphic: url("imgs/buttons/button.png");
   ...
}

.custom-button:hover {
   -fx-graphic: url("imgs/buttons/button_hover.png");
   ...
}

.custom-button:selected {
   -fx-graphic: url("imgs/buttons/button_selected.png");
   ...
}

I want to specify such transformation here in css as well. How can I achieve that? I am supposing to find something like:

.custom-button .graphic {
   -fx-rotate: 90;
}
rvit34
  • 1,967
  • 3
  • 17
  • 33

1 Answers1

7

Let's start with an example application:

Main.java

package application;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        Button button = new Button("Button");
        VBox vBox = new VBox(button);
        vBox.setPadding(new Insets(10.0));
        Scene scene = new Scene(vBox, 200, 100);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
        System.out.println();
    }

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

application.css

.button {
    -fx-graphic: url(image.png);
}

Result

image1

Method 1 (find out which class is used for the image)

This can be easily done using a debugger (set a breakpoint on println() and check the content of button.graphic.value). The class which is used here is ImageView. This means the image can be rotated using:

.button .image-view {
    -fx-rotate: 45;
}

Result

image2

Method 2 (set a custom class for the graphic object)

This can be done using a ChangeListener:

button.graphicProperty().addListener((ChangeListener<Node>) (observable, oldValue, newValue) -> {
    newValue.getStyleClass().add("my-class");
});

Then the following can be used to rotate the image:

.my-class {
    -fx-rotate: 45;
}

Result

image2

Padding

You might need to add additional padding to the button, if the image takes up too much space:

.button {
    -fx-graphic: url(image.png);
    -fx-graphic-text-gap: 10;
    -fx-label-padding: 5 0 5 5;
}

Result

image3

Sleafar
  • 1,486
  • 8
  • 10
  • Could you expand your explanation about how do you used a debugger for finding out a properly class name? – rvit34 Nov 07 '16 at 18:33
  • 1
    @rvit34 Added a short explanation and screenshot. – Sleafar Nov 07 '16 at 18:43
  • 2
    @rvit34 [ScenicView](http://fxexperience.com/scenic-view/) is also a useful tool for introspecting on components and layout. It will also display CSS style class information for components. – jewelsea Nov 07 '16 at 22:18