JavaFX子项影响父级的宽度

时间:2018-06-03 09:48:13

标签: java javafx

我有一个有两个孩子的HBox(一个ImageView和一个文本),但在某些条件下我想隐藏文字以强制HBox减少它。 我已经有了一个技术,它将managedProperty绑定到visibleProperty,但是它没有按预期工作,因为文本强制HBox宽度包含文本宽度。

我的问题是:如何禁用节点冲突(在他的父节点上),但不能将managedProperty设置为false。 (因为这个属性使它不再保持在正确的位置)

1 个答案:

答案 0 :(得分:0)

为此,您需要覆盖最小节点宽度的计算。如果您还想将节点的部分隐藏在边界之外,则需要将clip应用于布局。

示例:

public class ShrinkableHBox extends HBox {

    private final int unshrinkableCount;

    public ShrinkableHBox(int unshrinkableCount) {
        final Rectangle clip = new Rectangle();
        clip.widthProperty().bind(widthProperty());
        clip.heightProperty().bind(heightProperty());
        setClip(clip);
        this.unshrinkableCount = unshrinkableCount;
    }

    @Override
    protected double computeMinWidth(double height) {
        Insets insets = getInsets();
        height -= insets.getTop() + insets.getBottom(); 
        double width = insets.getLeft() + insets.getRight();

        List<Node> children = getManagedChildren();

        int unshrinkableCount = Math.min(children.size(), this.unshrinkableCount);

        // only consider the first unshrinkableCount children for minWidth computation
        if (unshrinkableCount > 1) {
            width += getSpacing() * (unshrinkableCount - 1);
        }

        for (int i = 0; i < unshrinkableCount; i++) {
            width += children.get(i).minWidth(height);
        }

        return width;
    }

}
@Override
public void start(Stage primaryStage) {
    // custom hbox with 2 resizeable 
    ShrinkableHBox hbox = new ShrinkableHBox(1);
    hbox.getChildren().addAll(
            new Rectangle(100, 100, Color.RED),
            new Rectangle(100, 100, Color.BLUE)
    );
    hbox.setOpacity(0.5);

    Scene scene = new Scene(new HBox(hbox, new Rectangle(100, 100, Color.GREEN.interpolate(Color.TRANSPARENT, 0.5))));
    primaryStage.setScene(scene);
    primaryStage.show();
}

请注意,简单地用Text替换Label节点也可能是一种解决方案,因为如果空间不足,可以使用省略号缩短文本。

相关问题