让我们从一个示例应用程序开始:
主.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);
}
}
应用程序.css
.button {
-fx-graphic: url(image.png);
}
结果

方法一(找出图片使用了哪个类)
这可以使用调试器轻松完成(在println()上设置断点并检查button.graphic.value的内容)。这里使用的类是ImageView。这意味着可以使用以下方法旋转图像:
.button .image-view {
-fx-rotate: 45;
}
结果

方法二(为图形对象设置自定义类)
这可以使用 ChangeListener 来完成:
button.graphicProperty().addListener((ChangeListener<Node>) (observable, oldValue, newValue) -> {
newValue.getStyleClass().add("my-class");
});
然后可以使用以下方法来旋转图像:
.my-class {
-fx-rotate: 45;
}
结果

填充
如果图像占用太多空间,您可能需要为按钮添加额外的填充:
.button {
-fx-graphic: url(image.png);
-fx-graphic-text-gap: 10;
-fx-label-padding: 5 0 5 5;
}
结果
