Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: AWT
Expertise: Beginner
Nov 5, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Scrollbar Value Notification

Is there a way that I can dynamically determine the value of a Scrollbar when I am scrolling? The adjustmentValueChanged method gets called only when you stop scrolling. But I want to catch the value of the scrollbar when I press on the scrollbar and I am dragging it. Is there a way to do this?

As most Java programmers know by now, you pay a price for the crossplatform portability of Java. Your code may compile once and run everywhere, but it may not behave the same way on every platform. The Scrollbar class is an AWT component in which the ultimate representation and behavior is determined by a native peer.

In Windows 95, you may find that the behavior of a Scrollbar is to notify its listeners of a change in value only after it has finished moving, rather than smoothly while it's moving. In a Unix/Motif environment, I find that each time the Scrollbar moves a unit increment, the listener is notified. Rather than rely on native peers, it is better to use the Java Foundation Classes, specifically the Swing package, to guarantee consistent behavior across platforms. The following example program allows you to test the behavior of java.awt.Scrollbar versus that of javax.swing.JScrollBar. A listener is registered with a scrollbar of each type, and prints out the scrollbar values each time it is notified of a change via the AdjustmentListener interface.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ScrollTest {

  public static class ScrollTestComponent extends JPanel
    implements AdjustmentListener
    JTextArea _scrollText;
    Scrollbar _scrollBar;
    JScrollBar _jscrollBar;

    public ScrollTestComponent() {
      _scrollBar  = new Scrollbar();
      _jscrollBar = new JScrollBar();
      _scrollText = new JTextArea(40, 40);
      setLayout(new BorderLayout());
      add(_scrollBar, BorderLayout.WEST);
      add(_scrollText, BorderLayout.CENTER);
      add(_jscrollBar, BorderLayout.EAST);

    public void printScrollValues() {
      _scrollText.setText("    ScrollBar: ");
      _scrollText.append("\n    JScrollBar: ");

    public void adjustmentValueChanged(AdjustmentEvent e) {


  public static void main(String[] args) {
    JFrame frame = new JFrame("Scroll Test");
    WindowListener exitListener;

    exitListener = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        Window window = e.getWindow();


    frame.getContentPane().add(new ScrollTestComponent(),

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date