Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a JScrollBar has reached the bottom of the JScrollPane?

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());
    }
}
like image 223
nathan Avatar asked Oct 16 '12 13:10

nathan


People also ask

What is the difference between JScrollPane and JScrollBar?

A JScrollBar is a component and it doesn't handle its own events whereas a JScrollPane is a Container and it handles its own events and performs its own scrolling.

How do I get rid of JScrollPane?

removeAll(); This removes all components added to the JScrollPanel .


1 Answers

You have to add the extent of the scrollbar to your calculation. I added the code into your code in the example below.

scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
    @Override
    public void adjustmentValueChanged(AdjustmentEvent ae) {
        int extent = scrollPane.getVerticalScrollBar().getModel().getExtent();
        System.out.println("Value: " + (scrollPane.getVerticalScrollBar().getValue()+extent) + " Max: " + scrollPane.getVerticalScrollBar().getMaximum());
    }
});

Two alternative implementations (partially reacting to Kleopatra)

scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {

    @Override
    public void adjustmentValueChanged(AdjustmentEvent event) {
        JScrollBar scrollBar = (JScrollBar) event.getAdjustable();
        int extent = scrollBar.getModel().getExtent();
        System.out.println("1. Value: " + (scrollBar.getValue() + extent) + " Max: " + scrollBar.getMaximum());

    }
});

Or via the model

scrollPane.getVerticalScrollBar().getModel().addChangeListener(new ChangeListener() {

    @Override
    public void stateChanged(ChangeEvent event) {
        BoundedRangeModel model = (BoundedRangeModel) event.getSource();
        int extent = model.getExtent();
        int maximum = model.getMaximum();
        int value = model.getValue();

        System.out.println("2. Value: " + (value + extent) + " Max: " + maximum);

    }
});
like image 155
JeroenWarmerdam Avatar answered Oct 19 '22 02:10

JeroenWarmerdam