How can I check if I've scrolled to the bottom of a scrollable panel

What I’m trying to do with this chat box is when a user sends a message should auto scroll. But if the user is scrolled up while viewing previous messages, do not autoscroll.

What I’ve already tried below is when a new line is added to the chat message, hold the current Y offset, scroll to the bottom of the chat, record that offset and then compare the two offsets. If the offsets are not the same, then scroll back to the original position.

Although this doesn’t work because the value for maximumHeight is 32767 which is highest value for a SHORT. I thought it would be the maximum height of the content for panel.

panel = new Panel();
panelLayout = new CssLayout();
panelLayout.setStyleName("chatlog");
panel.setContent(panelLayout);
addComponent(panel);
panel.setSizeFull();
setExpandRatio(panel, 1);

// add text to panel until scroll bar appears
//...

// Scroll to bottom if position is already at bottom, else keep same scroll position
int currentPosition = panel.getScrollTop();
panel.setScrollTop(Short.MAX_VALUE);
int maximumHeight = panel.getScrollTop();

if (currentPosition == maximumHeight) {
  panel.setScrollTop(Short.MAX_VALUE);
} else {
  panel.setScrollTop(currentPosition);
}