Skip to content
Advertisement

Keeping a JScrollPane’s (JTextPane) scroll bar at the bottom when resizing text?

Very weird problem: I have a JTextPane within a JScrollPane, and a JSlider for resizing the text. If I increase the text size, the scroll bar moves up (normal). My goal is to keep the scroll bar at the bottom, if it was at the bottom before resizing the text. The weird thing is, I can ONLY get it to work if I throw in a JOptionPane (dialog) towards the end of the ChangeListener. If I don’t include the dialog (comment out line 92), the scroll bar still moves up when increasing text size, apparently ignoring line 100.

Another thing: if I click to change the text size, the dialog window freaks out, popping up multiple times and screwing up the slider. However, if I use Tab to select the slider and then arrow keys to move it up and down, the dialog window acts normally, and the scroll bar will do what I want it to.

So, actually two mysteries here:

  1. Why does line 100, which sends the scroll bar to the bottom, only seem to work if it’s preceded by a dialog popup (line 92)?
  2. Why does the dialog/slider get all screwy when using a mouse to move the slider, but not when using Tab+arrow keys?

This is driving me bonkers. Good luck and thanks!

JavaScript

Advertisement

Answer

I modified your code to create the following GUI.

Scroll Test

The major changes I made are in the stateChanged method. I added the test for the slider to stop moving and the JFrame pack. The JFrame pack makes sure all the Swing components have resized properly.

Here’s the complete runnable code.

JavaScript
Advertisement