1

I made an extension of the JavaFX ListView component :

HL7ListView extends ListView<String>

The goal is for it to auto-scroll the parent ScrollPane as new items are added to it. I have a constructor that takes the ScrollPane in question as an argument and I made an addItem() method like this :

public void addItem(String item)
{
    List<String> items = getItems();
    items.add(item);

    scrollTo(items.size());

    scrollPane.setVvalue(1.0);
}

The auto scrolling only works when i manually scroll to the bottom once to "get it going" if that makes any sense. Once it is scrolled to the bottom, new items behave as expected and the scrollbar goes down automatically, trailing the ListView's content. Not sure what could be the problem here, obviously the scroll bar only appears when there is a need for it, not sure if that could have anything to do with this.

Any idea?

Martin
  • 1,977
  • 5
  • 30
  • 67

1 Answers1

1

I think you DON'T need to wrap your ListView with parent ScrollPane as ListView has the built-in scroller. You can use scrollTo() to scroll with the last index directly.

ListView<String> listView = new ListView<>();
listView.getItems().addAll(items);

listView.scrollTo(listView.getItems().size() - 1);

Edit

Using super.scrollTo instead of this.scrollTo seems to work on your extenstion (HL7ListView) as well,

class HL7ListView extends ListView<String> {

    public HL7ListView() {
    }

    public HL7ListView(List<String> items) {
        this.getItems().addAll(items);
        super.scrollTo(getItems().size() - 1);
    }

    public void addItem(String item) {
        this.getItems().add(item);
        super.scrollTo(getItems().size() - 1);

    }
}

PS: I tried to wrap with ScrollPane as your approach and went through this QA - and that's not working, it seems kinda bug.

Shekhar Rai
  • 2,008
  • 2
  • 22
  • 25
  • I changed the scrollTo to the size - 1 and removed the setVvalue call on the scrollpane and i'm still seeing the same behavior. It only starts trailing when i manually scroll down to the end when the scrollbar appears. – Martin Jan 03 '20 at 18:51
  • @Martin my bad! I tested directly with list view and set `size-1` and that worked and I supposed that extending ListView should have the same behaviour but It's not working(not sure why). maybe I had to use `super.scrollTo` - anyway, I updated the code, which works smoothly. – Shekhar Rai Jan 03 '20 at 18:59
  • 1
    I got it to work! I realized i was still calling getItems().add() instead of my custom addItem() method (DOH). I removed the ScrollPane and replaced it with a simple BorderPane, you are correct, it is completely unnecessary and the ListView has its own scrollbar. Thanks! – Martin Jan 03 '20 at 19:23