ListView 的可见项

ale*_*lex 2 listview javafx

有没有办法获取 aListView中的可见项目JavaFX?我想确定ListView我的应用程序中显示的第一个可见项目JavaFX。

此处找到的以下代码对我不起作用(仅适用于 a TableView):

@SuppressWarnings("restriction")
public void getFirstAndLast(ListView<?> t) {
    try {
        ListViewSkin<?> ts = (ListViewSkin<?>) t.getSkin();
        VirtualFlow<?> vf = (VirtualFlow<?>) ts.getChildren().get(0);
        first = vf.getFirstVisibleCell().getIndex();
        last = vf.getLastVisibleCell().getIndex();
    }catch (Exception ex) {}
}

public int getFirst() {
    return first;
}

public int getLast() {
    return last;
}
Run Code Online (Sandbox Code Playgroud)

ale*_*lex 5

正如@James_D 所解释的,没有一个很好的开箱即用的解决方案,但只有黑客才能工作。我采用了在网上找到的解决方案,如下所示。

[...]
private int first = 0;
private int last  = 0;

public void getFirstAndLast(ListView<?> t) {
    try {
        ListViewSkin<?> ts = (ListViewSkin<?>) t.getSkin();
        VirtualFlow<?> vf = (VirtualFlow<?>) ts.getChildren().get(0);
        first = vf.getFirstVisibleCell().getIndex();
        last = vf.getLastVisibleCell().getIndex();
        logger.debug("##### Scrolling first {} last {}", first, last);
    } catch (Exception ex) {
        logger.debug("##### Scrolling: Exception " + ex);
    }
}

public int getFirst() {
    return first;
}

public int getLast() {
    return last;
}
[...]
Run Code Online (Sandbox Code Playgroud)

输出示例:

13:56:38.652 [X 应用程序线程] DEBUG getFirstAndLast - 滚动 #### 前 11 后 20 13:56:48.503 [X 应用程序线程] 调试 getFirstAndLast - 滚动 #### 前 9 后 17 13:57:08.491 [ X 应用程序线程] DEBUG getFirstAndLast - 滚动 #### 前 7 后 15 13:57:18.371 [X 应用程序线程] DEBUG getFirstAndLast - 滚动 #### 前 3 后 15