讓我們先從一個示例應用程序:
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);
}
結果
方法1(找出哪些類是用於圖像)
這可以使用調試器(set a breakpoint on println() and check the content of button.graphic.value)被容易地完成。這裏使用的類是ImageView。這意味着圖像可以使用旋轉:
.button .image-view {
-fx-rotate: 45;
}
結果
方法2(設置自定義類的圖形對象)
這可以使用進行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;
}
和
結果
感謝。這是有幫助的。 – rvit34
你可以擴展你的解釋:你如何使用調試器來找出正確的類名? – rvit34
@ rvit34添加了一個簡短的說明和截圖。 – Sleafar