Skip to content
Advertisement

How do I enable a button after the scrollbar goes to the bottom?

So, I used a JScrollPane and then I added a JTextArea. I used textArea.setCaretPosition(0) to reset the scroll and it went at the top. All good, until I wanted to set a disabled Button on enable when the scrollbar reaches at the bottom.

How can I do that?

Advertisement

Answer

You can listen for changes to the JScrollPane’s viewport, and compare the bottom of the viewport’s visible rectangle with the height of the viewport’s view (that is, the JTextArea):

JViewport viewport = scrollPane.getViewport();
viewport.addChangeListener(e -> {
    Rectangle rect = viewport.getViewRect();
    int bottom = rect.y + rect.height;
    endButton.setEnabled(bottom >= viewport.getViewSize().height);
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement