我在自定义 JavaFX 控件中使用带有文本的 TextFlow,并且该控件放置在 TitledPane 中。
控制声明:
public class CustomControl extends Control {
@Override
protected Skin<?> createDefaultSkin() {
return new CustomControlSkin(this);
}
}
皮肤声明:
public class CustomControlSkin extends SkinBase<CustomControl> implements Skin<CustomControl> {
public CustomControlSkin(CustomControl customControl) {
super(customControl);
TextFlow textFlow = new TextFlow();
textFlow.getChildren().add(new Text("This is a long long long long long long long long long long long long long long text"));
getChildren().add(new StackPane(textFlow));
}
}
应用:
@Override
public void start(Stage primaryStage) throws Exception {
TitledPane titledPane = new TitledPane();
titledPane.setContent(new CustomControl());
Scene scene = new Scene(new StackPane(titledPane));
primaryStage.setScene(scene);
primaryStage.show();
}
当场景水平调整大小时,文本会换行并且其高度会增加。但是,TitledPane 不会垂直调整大小。
当 TextFlow 直接放置在 TitledPane 中而不使用自定义控件时,不会发生这种情况。
使用Scenic View我注意到,当在自定义控件中使用 TextFlow 时,控件的布局边界与父级中的边界不同。实际上,parent 中的边界似乎是正确计算的,但没有使用。
这可能是此问题的根源。我已经尝试过皮肤的所有计算(最小/首选/最大)高度方法,但未能正确调整 TitledPane 的大小。
知道为什么 TextFlow 在自定义控件/皮肤中使用时表现不同,以及如何正确调整 TitledPane 的大小吗?
最佳答案
我向 Oracle 报告了此问题,这被视为 JavaFX 错误:JDK-8144128
作为解决此错误的方法,我执行了以下操作:
将控件内容偏差设置为 Orientation.HORIZONTAL
public class CustomControl extends Control { @Override protected Skin<?> createDefaultSkin() { return new CustomControlSkin(this); } @Override public Orientation getContentBias() { return Orientation.HORIZONTAL; } }
覆盖皮肤computeMinHeight以在调用node.minHeight时使用节点宽度而不是-1
public class CustomControlSkin extends SkinBase<CustomControl> implements Skin<CustomControl> { public CustomControlSkin(CustomControl customControl) { super(customControl); TextFlow textFlow = new TextFlow(); textFlow.getChildren().add(new Text("This is a long long long long long long long long long long long long long long text")); getChildren().add(new StackPane(textFlow)); } @Override protected double computeMinHeight(double width, double topInset, double rightInset, double bottomInset, double leftInset) { double minY = 0; double maxY = 0; boolean firstManagedChild = true; for (int i = 0; i < getChildren().size(); i++) { Node node = getChildren().get(i); if (node.isManaged()) { final double y = node.getLayoutBounds().getMinY() + node.getLayoutY(); if (!firstManagedChild) { minY = Math.min(minY, y); maxY = Math.max(maxY, y + node.minHeight(width)); } else { minY = y; maxY = y + node.minHeight(width); firstManagedChild = false; } } } double minHeight = maxY - minY; return topInset + minHeight + bottomInset; } }
关于layout - 在自定义控件中使用 TextFlow 时,TitledPane 未垂直调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33825689/