Java Swing How to - Detect if a JScrollPane's scroll bar changes visibility








Question

We would like to know how to detect if a JScrollPane's scroll bar changes visibility.

Answer

import java.awt.BorderLayout;
import java.io.UnsupportedEncodingException;
//from  w w w.j  a va 2  s  . c  om
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingWorker;

public class Main {
  public static void main(String[] args) throws UnsupportedEncodingException {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JPanel buttons = new JPanel();
    JScrollPane pane = new JScrollPane(buttons);
    pane.getViewport().addChangeListener(
        e -> {
          System.out.println("Change in " + e.getSource());
          System.out.println("Vertical visible? "
              + pane.getVerticalScrollBar().isVisible());
          System.out.println("Horizontal visible? "
              + pane.getHorizontalScrollBar().isVisible());
        });
    panel.add(pane);
    frame.setContentPane(panel);
    frame.setSize(300, 200);
    frame.setVisible(true);
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
      @Override
      protected Void doInBackground() throws Exception {
        for (int i = 0; i < 10; i++) {
          Thread.sleep(800);
          buttons.add(new JButton("Hello " + i));
          buttons.revalidate();
        }
        return null;
      }
    };
    worker.execute();
  }
}