You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX:如何获取Rectangle的xProperty最小值存入DoubleProperty?

解决JavaFX中获取DoubleProperty流最小值并写入DoubleProperty的问题

错误原因

你调用stream().map(Rectangle::xProperty).min()报错,是因为Stream<DoubleProperty>的min()方法必须传入Comparator来定义比较规则,无参的min()只适用于DoubleStream这类数值流。


解决方案

1. 一次性计算当前最小值(非响应式)

直接提取每个Rectangle的x值转为数值流,调用无参min()获取最小值,再设置到目标DoubleProperty:

ArrayList<Rectangle> rectangles = ...; // 你的Rectangle列表
DoubleProperty minX = new SimpleDoubleProperty();

rectangles.stream()
    .mapToDouble(Rectangle::getX) // 提取x的当前数值
    .min()
    .ifPresent(minX::set); // 列表非空时将最小值写入minX

2. 响应式绑定(自动更新最小值)

如果需要当任意Rectangle的x坐标变化时,minX自动同步更新,用Bindings.createDoubleBinding实现绑定:

DoubleProperty minX = new SimpleDoubleProperty();

// 绑定逻辑:依赖所有Rectangle的xProperty,自动计算最小值
minX.bind(Bindings.createDoubleBinding(() -> 
    rectangles.stream()
        .mapToDouble(Rectangle::getX)
        .min()
        .orElse(0.0), // 列表为空时的默认值,可按需修改
    // 传入所有xProperty作为绑定依赖项
    rectangles.stream()
        .map(Rectangle::xProperty)
        .toArray(DoubleProperty[]::new)
));

3. 直接对DoubleProperty流使用Comparator

如果你坚持操作DoubleProperty流,给min()传入比较器也能实现:

rectangles.stream()
    .map(Rectangle::xProperty)
    .min(Comparator.comparingDouble(DoubleProperty::get))
    .ifPresent(minProp -> minX.set(minProp.get()));

内容的提问来源于stack exchange,提问作者Keen Teen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:35:06