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

Here is my code for the ScrollPane

    public class CustomScrollPane extends JScrollPane {

    private static CustomScrollPane instance = null;

    public CustomScrollPane () {
        super(panel.getInstance()); // a panel that the scrollpane wraps around
        this.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        // hide the vertical scroll bar
        this.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));
    }

    public static CustomScrollPane getInstance() {
        if (instance == null)
            instance = new CustomScrollPane ();
        return instance;
    }

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

public void scrollToBottom() { getVerticalScrollbar().getMaximum(); }

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

Any help would be appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source