I've got a viewport, and I've attached a change listener to it. Whenever I scroll through my viewport, my change listener gets called about four times. I'm not sure how to avoid this; I only want the call to happen once?
Why does viewport changelistener get called multiple times
1.2k views Asked by 3uPh0riC At
2
There are 2 answers
3
On
You can try to use AdjustmentListener
for gettign scroll event once, try next:
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.io.UnsupportedEncodingException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Example {
public static void main(String[] args) throws UnsupportedEncodingException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JScrollPane pane = new JScrollPane(new JTextArea());
pane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
if(e.getValueIsAdjusting()){
return;
}
System.out.println("vertical scrolled");
System.out.println("bar value = " + e.getValue());
}
});
frame.setContentPane(pane);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Here is another example.
There's no way around this,
JViewport
will fire severalstateChanged
events because it's providing notification about changes to a number of properties...From the JavaDocs...
At this point, it's kind of hard to know what to suggest as we don't know what it is you are trying to achieve, however, if you have to use a
ChangeListener
, you could set up a coalescing mechanism. That is, rather then responding to each event, you basically wait until a long enough delay has occurred between events before responding to it...For example...
Basically, this is a
ChangeListener
implementation that uses a non-repeatingjavax.swing.Timer
with a short delay. Each timestateChanged
is called, the timer is restart. Finally, when the timer is allowed to "tick", it callsstableStateChanged
indicating that enough time has passed since the last event was raised.This assumes that you don't so much care about what caused the event, only that the event occured...
A runnable example...