JavaFX中如何在保持按钮尺寸不变的情况下增大按钮字体图标?
如何让带图标的按钮与纯文本按钮保持相同高度(JavaFX + CSS,仅用em单位)
我在工具栏中有两个按钮,一个仅包含文本,另一个同时包含字体图标和文本。文本大小与图标大小均使用em单位设置(不使用px!)。我希望增大图标尺寸,但需保持两个按钮高度一致。
Java代码
public class NewMain extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { var textButton = new Button("SomeText"); var fontIcon = new Label("A"); fontIcon.getStyleClass().add("my-icon"); var textAndIconButton = new Button("SomeText", fontIcon); textAndIconButton.getStyleClass().add("icon-button"); var toolBar = new ToolBar(textButton, textAndIconButton); toolBar.setMinHeight(40); var root = new VBox(toolBar); var scene = new Scene(root, 400, 200); scene.getStylesheets().add(NewMain.class.getResource("style.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); } }
原始CSS代码
.root { -fx-font-size:16px; } .button { -fx-padding: 0.4em; -fx-font-size: 1em; } .my-icon { -fx-font-size: 1.4em; } .icon-button { -fx-padding: 0.2em 0.4em 0.2em 0.4em; }
解决方法
核心是强制所有按钮的高度一致,同时调整带图标按钮的内边距来容纳更大的图标,全程使用em单位:
修改后的CSS:
.root { -fx-font-size:16px; } .button { -fx-padding: 0.4em; -fx-font-size: 1em; /* 固定按钮高度:文本高度1em + 上下内边距0.4em*2 = 1.8em */ -fx-min-height: 1.8em; -fx-max-height: 1.8em; -fx-alignment: center; /* 确保内容垂直居中 */ } .my-icon { -fx-font-size: 1.4em; -fx-alignment: center; /* 让图标和文本垂直对齐 */ } .icon-button { /* 减少上下内边距,总高度保持1.8em:图标高度1.4em + 上下内边距0.2em*2 = 1.8em */ -fx-padding: 0.2em 0.4em; }
原理说明
- 先计算纯文本按钮的总高度:
文本高度(1em) + 上下内边距(0.4em×2)= 1.8em,将这个值设为所有按钮的固定高度(-fx-min-height和-fx-max-height),强制高度统一。 - 带图标的按钮中,图标高度(1.4em)比文本高,因此将上下内边距各减少0.2em,总高度仍为
1.4em + 0.2em×2 = 1.8em,和纯文本按钮一致。 - 设置
-fx-alignment: center保证按钮内的文本、图标都垂直居中,视觉上更协调。
内容的提问来源于stack exchange,提问作者SilverCube
相关产品推荐
相关产品推荐

