Skip to content
Advertisement

How to make JScrollPane dynamically scroll to the end after adding components?

Here is my code for the ScrollPane

JavaScript

I tried to do getVerticalScrollbar.setValue(getVerticalScrollbar().getMaximum()) but it does not scroll to the end when I add JLabels to it. I’m trying to make it so that it will always scroll to the bottom of the screen once a new JLabel gets added to the panel. I din’t use JTextArea as I want each line to have a different foreground color, so I used JLabels.

I also tried adding this method

JavaScript

but it just freezes the ScrollPane and I am unable to scroll.

Any help would be appreciated!

Advertisement

Answer

I’m not sure what you hope to achieve by extending JScrollPane, not sure that it’s really its core responsibility, after all, you could have its “viewport view” do it itself, for example…

enter image description here

JavaScript

The magic is right here…

JavaScript

Here, I’m asking the contentPane (which is the container holding all the squares) to “scroll to a visible rectangle” based on my needs

Now, in you case, when you add a new component to the “container”, you would need to instruct the component to scroll to a position which would show the new component.

This is going to be a little more complicated as you will need to trigger a layout pass first, so you can get the new size of the container

Dynamic addition to the container…

JavaScript

Now, if you really wanted to decouple the concept, you could us a ContainerListener and react to the new component been added via it

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement