如何让含按钮与Text的JavaFX AnchorPane点击时实现按钮式内边距效果?
解决AnchorPane点击时的内边距效果问题
首先,你遇到的问题核心在于AnchorPane的-fx-padding属性不会影响它的子元素位置——因为AnchorPane的子节点是通过layoutX/layoutY进行绝对定位的,padding只会改变AnchorPane自身的边界,不会让内部的Text跟着偏移,所以看起来没有效果。
下面给你两个可行的解决方案,根据你的需求选择:
方案1:用Button替代AnchorPane(推荐)
既然你本来就需要按钮的点击效果,直接把AnchorPane换成Button是最省心的方式,Button原生支持:pressed状态下的padding偏移,而且内部元素会自动调整位置。
修改后的FXML:
<Button id="sickleButton" fx:id="sickleButton" layoutX="65.0" layoutY="68.0" prefHeight="90.0" prefWidth="309.0" onMouseClicked="#onSickleButtonClicked" stylesheets="@style.css"> <children> <Text fx:id="sickleLevelLabel" layoutX="193.0" layoutY="27.0" strokeType="OUTSIDE" strokeWidth="0.0" text="1" wrappingWidth="95.13671875"> <font> <Font size="24.0" /> </font> </Text> <Text fx:id="sickleUpCostLabel" layoutX="129.0" layoutY="66.0" strokeType="OUTSIDE" strokeWidth="0.0" text="10" wrappingWidth="60.136717826128006"> <font> <Font size="20.0" /> </font> </Text> <Text fx:id="sickleIncomeLabel" layoutX="237.0" layoutY="66.0" strokeType="OUTSIDE" strokeWidth="0.0" text="2" wrappingWidth="51.749999821186066"> <font> <Font size="20.0" /> </font> </Text> </children> </Button>
修改后的CSS:
#sickleButton{ -fx-background-image: url(../Resources/sicklebutton.png); -fx-background-size: 300 80; -fx-background-repeat: no-repeat; -fx-background-color: rgba(0,0,0,0); -fx-border-width: 0; /* 去掉按钮默认边框 */ } #sickleButton:hover{ -fx-effect:dropshadow(gaussian, rgba(0, 8, 29, 1), 10, 0, 0, 0); -fx-cursor: hand; } #sickleButton:pressed{ -fx-effect:dropshadow(gaussian, rgba(0, 8, 29, 1), 30, 0, 0, 0); -fx-padding: 5 5 0 0; /* 右下偏移,模拟按下的内边距效果 */ } #sickleButton:disabled { -fx-opacity: 0.6; }
这里的-fx-padding: 5 5 0 0会让按钮内部的所有元素向右下偏移,完美模拟按钮按下的凹陷感,而且不需要手动调整每个Text的位置。
方案2:保留AnchorPane,通过偏移子元素实现效果
如果一定要保留AnchorPane,我们可以通过CSS的-fx-translate-x/-fx-translate-y属性,让所有子Text在点击时偏移,同时调整背景图的位置:
修改后的CSS:
#pane{ -fx-background-image: url(../Resources/sicklebutton.png); -fx-background-size: 300 80; -fx-background-repeat: no-repeat; -fx-background-color: rgba(0,0,0,0); -fx-background-position: 0 0; /* 初始背景位置 */ } #pane:hover{ -fx-effect:dropshadow(gaussian, rgba(0, 8, 29, 1), 10, 0, 0, 0); -fx-cursor: hand; } #pane:pressed{ -fx-effect:dropshadow(gaussian, rgba(0, 8, 29, 1), 30, 0, 0, 0); -fx-background-position: 5 5; /* 背景图右下偏移 */ } /* 让所有Text子元素在按下时偏移 */ #pane:pressed .text { -fx-translate-x: 5; -fx-translate-y: 5; } #pane:disabled { -fx-opacity: 0.6; }
这个方案通过同步移动背景图和内部文字,达到类似内边距的视觉效果,缺点是需要确保所有子元素都被选中(这里用.text选择器匹配所有Text节点)。
内容的提问来源于stack exchange,提问作者Beforeu
相关产品推荐
相关产品推荐

