Question:
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?
Answer:
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();
_scrollBar.addAdjustmentListener(this);
_jscrollBar.addAdjustmentListener(this);
_scrollText = new JTextArea(40, 40);
_scrollText.setEditable(false);
setLayout(new BorderLayout());
add(_scrollBar, BorderLayout.WEST);
add(_scrollText, BorderLayout.CENTER);
add(_jscrollBar, BorderLayout.EAST);
printScrollValues();
}
public void printScrollValues() {
_scrollText.setText(" ScrollBar: ");
_scrollText.append(Integer.toString(_scrollBar.getValue()));
_scrollText.append("\n JScrollBar: ");
_scrollText.append(Integer.toString(_jscrollBar.getValue()));
}
public void adjustmentValueChanged(AdjustmentEvent e) {
printScrollValues();
}
}
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();
window.setVisible(false);
window.dispose();
System.exit(0);
}
};
frame.addWindowListener(exitListener);
frame.getContentPane().add(new ScrollTestComponent(),
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}