JavaFX:含MFXToggleButton的VBox无法折叠收缩的问题求助
VBox折叠失效问题的解决办法
核心问题原因
VBox默认会根据子节点的最小高度(minHeight)和布局边距计算自身最小尺寸,即便手动设置height,只要子节点的最小高度总和加边距大于目标值,VBox就无法缩小到指定高度。另外MFXToggleButton可能自带固定最小高度,你设置的VBox.margin也会额外占据空间,这些都是阻碍折叠的关键因素。
具体解决步骤
1. 强制限制VBox的最小高度
给VBox设置minHeight="0",同时将prefHeight绑定到折叠状态,折叠时设为0,展开时用自动计算尺寸:
<VBox minHeight="0" prefHeight="${controller.expanded ? USE_COMPUTED_SIZE : 0}"> <!-- 子节点内容 --> </VBox>
2. 重置MFXToggleButton的最小高度
MFXToggleButton通常有默认最小高度,需要手动覆盖为0,确保折叠时能彻底收缩:
<MFXToggleButton minHeight="0" ...> <!-- 其他属性 --> </MFXToggleButton>
3. 用绑定属性控制边距与可见性
通过布尔属性绑定控制按钮的边距和布局占用,折叠时清空边距并让节点不占布局空间:
<MFXToggleButton text="Installed" visible="${controller.expanded}" managed="${controller.expanded}"> <VBox.margin> <Insets top="${controller.expanded ? 20 : 0}" bottom="${controller.expanded ? 5 : 0}" left="10" /> </VBox.margin> </MFXToggleButton>
4. 控制器中定义状态属性
在Controller里创建布尔属性,用来统一控制折叠/展开状态:
public class SettingsController { public final BooleanProperty expanded = new SimpleBooleanProperty(true); // 可添加手动切换方法 public void toggleSettings() { expanded.set(!expanded.get()); } }
完整示例代码
<VBox minHeight="0" prefHeight="${controller.expanded ? USE_COMPUTED_SIZE : 0}"> <!-- 总开关按钮 --> <MFXToggleButton text="Toggle Settings" selected="${controller.expanded}"> <VBox.margin> <Insets top="10" left="10" /> </VBox.margin> </MFXToggleButton> <MFXToggleButton selected="true" text="Installed" minHeight="0" visible="${controller.expanded}" managed="${controller.expanded}"> <VBox.margin> <Insets top="20" bottom="5" left="10" /> </VBox.margin> </MFXToggleButton> <MFXToggleButton selected="true" text="Releases" minHeight="0" visible="${controller.expanded}" managed="${controller.expanded}"> <VBox.margin> <Insets top="10" bottom="5" left="10" /> </VBox.margin> </MFXToggleButton> <MFXToggleButton selected="true" text="Modified" minHeight="0" visible="${controller.expanded}" managed="${controller.expanded}"> <VBox.margin> <Insets top="10" bottom="5" left="10" /> </VBox.margin> </MFXToggleButton> <MFXToggleButton selected="false" text="Snapshots" minHeight="0" visible="${controller.expanded}" managed="${controller.expanded}"> <VBox.margin> <Insets top="10" bottom="5" left="10" /> </VBox.margin> </MFXToggleButton> <MFXToggleButton selected="false" text="Olds" minHeight="0" visible="${controller.expanded}" managed="${controller.expanded}"> <VBox.margin> <Insets top="10" bottom="20" left="10" /> </VBox.margin> </MFXToggleButton> </VBox>
内容的提问来源于stack exchange,提问作者0xLairon1
相关产品推荐
相关产品推荐

