I'd like to know if there is a way to know when a JScrollBar
(vertical in my case) has reached the bottom of his containing JScrollPane
.
At first i have though of using an AdjustmentListener
on the scroll bar but i don't know how to interpret the value
attribute of the JScrollBar
. Also i'm not sure to properly understand what the maximum
represents and if i can use with the value to get the information i need.
Edit:
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent ae) {
System.out.println("Value: " + scrollPane.getVerticalScrollBar().getValue() + " Max: " + scrollPane.getVerticalScrollBar().getMaximum());
}
}
You have to add the extent of the scrollbar to your calculation. I added the code into your code in the example below.
Two alternative implementations (partially reacting to Kleopatra)
Or via the model
By using the viewport of the JScrollPane you can calculate if the viewport is viewing the end of the component.
@StanislavL almost had the correct answer.
Try
scrollBar.getValue() == scrollBar.getMaximum() - scrollBar.getVisibleAmount()
.To understand why the
getVisibleAmount()
call is necessary, you must first understand how JScrollBars work. A JScrollBar has 4 values: minimum, maximum, value, and extent.value
is the top of the scroll handle itself, andextent
is the effective length of the scroll handle.value
will never equalmaximum
unless the scroll handle has a length of 0. To compensate, we must adjust the value we are comparing against by subtracting the length of the scroll handle to get the effective maximum.This effect is documented here, which misleadingly makes it sound like
getMaximum()
adjusts the value like it should, but looking closely at the implementation of JScrollBar shows thatgetMaximum()
actually gives us the true maximum, not the effective maximum.