Я искал эту проблему, когда пытался реализовать кинетическую панель прокрутки, похожую на свитки для iPhone Apple. Элементы в TreeSet
являются этим классом:
/**
* Data object that contains a {@code DoubleExpression} bound to an item's
* relative distance away from the current {@link ScrollPane#vvalueProperty()} or
* {@link ScrollPane#hvalueProperty()}. Also contains the item index of the
* scrollable content.
*/
private static final class ItemOffset implements Comparable<ItemOffset> {
/**
* Used for floor or ceiling searches into a navigable set. Used to find the
* nearest {@code ItemOffset} to the current vValue or hValue of the scroll
* pane using {@link NavigableSet#ceiling(Object)} or
* {@link NavigableSet#floor(Object)}.
*/
private static final ItemOffset ZERO = new ItemOffset(new SimpleDoubleProperty(0), -1);
/**
* The current offset of this item from the scroll vValue or hValue. This
* offset is transformed into a real pixel length of the item distance from
* the current scroll position.
*/
private final DoubleExpression scrollOffset;
/** The item index in the list of scrollable content. */
private final int index;
ItemOffset(DoubleExpression offset, int index) {
this.scrollOffset = offset;
this.index = index;
}
/** {@inheritDoc} */
@Override
public int compareTo(ItemOffset other) {
double d1 = scrollOffset.get();
double d2 = other.scrollOffset.get();
if (d1 < d2) {
return -1;
}
if (d1 > d2) {
return 1;
}
// Double expression has yet to be bound
// If we don't compare by index we will
// have a lot of values ejected from the
// navigable set since they will be equal.
return Integer.compare(index, other.index);
}
/** {@inheritDoc} */
@Override
public String toString() {
return index + "=" + String.format("%#.4f", scrollOffset.get());
}
}
DoubleExpression
может занять некоторое время, чтобы быть связанным в runLater задаче платформы JavaFX, поэтому индекс входят в этом классе обертки.
Поскольку scrollOffset
всегда меняется в зависимости от положения прокрутки пользователя на колесе прокрутки, нам нужен способ обновления. Обычно порядок всегда один и тот же, поскольку смещение относительно позиции позиции элемента. Индекс никогда не изменяется, но смещение может быть отрицательным или положительным в зависимости от относительного расстояния элементов от текущего значения vValue или hValue для ScrollPane
.
Чтобы обновить по запросу только при необходимости, просто следуйте указаниям вышеприведенного ответа Tucuxi.
ItemOffset first = verticalOffsets.first();
verticalOffsets.remove(first);
verticalOffsets.add(first);
где verticalOffsets является TreeSet<ItemOffset>
. Если вы выполняете печать из , установленного каждый раз, когда вызывается этот фрагмент обновления, вы увидите, что он обновлен.
+1 nice question – skaffman
Это просто болезненное любопытство, или вы ищете конкретную выгоду, скажем, в простоте или простоте кода? – greim
Я искал простой неинвазивный способ поддержания порядка сортировки коллекции, поскольку события обновляют объекты внутри нее. Изменение членства имеет побочные эффекты для других потребителей коллекции. IMO, запускающий курортный элемент, кажется базовой базой для сортированной коллекции. – Stevko