快速问题,如何让图像覆盖 fxml 中的整个按钮。
所以按钮的所有可见部分都是边框。由于某种原因,当我尝试调整图像大小以适应按钮时,会自动调整大小。我正在使用场景生成器。 我正在使用 FXML。
按钮大小为 prefHeight="38.0"prefWidth="50.999900000002526"。
记住我不想看到按钮的背景。我希望它被图像覆盖。
非常感谢,你们帮了很大的忙。
最佳答案
您正在寻找的是使用填充
setPadding
public final void setPadding(Insets value);
Sets the value of the property padding.
Property description: The top, right, bottom, and left padding around the region's content. This space will be included in the calculation of the region's minimum and preferred sizes. By default padding is Insets.EMPTY. Setting the value to null should be avoided.
它没有提到默认值,但您可以通过输入 button.getPadding();
我决定自己测试一下,得到的值为
Insets [top=4.0, right=8.0, bottom=4.0, left=8.0]
这就是为什么您遇到它未填满的问题的原因。调整大小会影响按钮,图形是按钮的一部分。
接下来我们必须定义我们的插图以获得所需的效果。
为了定义我们的填充,我们需要查看插图
https://docs.oracle.com/javase/8/javafx/api/javafx/geometry/Insets.html
有一个 Empty
的静态字段,所以让我们使用它。
Button btn = new Button();
btn.setGraphic(new ImageView("image"));
btn.setPadding(Insets.EMPTY);
将产生所需的效果,并产生结果
Insets [top=0.0, right=0.0, bottom=0.0, left=0.0]
但是...仍然有一个边框,可能只有在焦点对准时才会出现...
如果您想摆脱边框,请阅读下文。
我决定测试负值是否有效,-1 确实有效。
本质上,如果您为插图指定 -1 值,它将切断按钮周围的边框,因此按钮本质上是一个图像
public class JavaFXApplication extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setGraphic(new ImageView(image));
btn.setPadding(new Insets(-1,-1,-1,-1));
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println(btn.getPadding());
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Button Image!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
关于javafx - 图像按钮javafx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37473207/