Search code examples
javaswingjscrollpanejtextareajscrollbar

Limiting a JScrollPane's scroll range


I have a JTextArea wrapped in a JScrollPane, which I use to log my application's output. I'm using the default, plain font with a size of 9 for the text area, and the scroll pane's height is 48 px. This results in an even distribution of lines in the scroll pane view, but there's a problem: if you scroll all the way up or all the way down, this happens:

enter image description here

As you can see, the top line got cut off, which is why I'm wondering if there's a way to limit the scroll pane's scroll range so it, for example, can't reach the top or bottom 6 pixels. Alternative solutions are also welcome.


Solution

  • You could change the margin (top/bottom) of your JTextArea by setting a custom Border using the method setBorder inherited from JComponent. The documentation for JComponent suggests the following:

    Although technically you can set the border on any object that inherits from JComponent, the look and feel implementation of many standard Swing components doesn't work well with user-set borders. In general, when you want to set a border on a standard Swing component other than JPanel or JLabel, we recommend that you put the component in a JPanel and set the border on the JPanel.

    That would yield the same result as limiting the scroll range, while being more straight forward.

    EDIT:

    OP reported that the following solution worked for him:

    textAreaLog.setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 6));