I have created a large panel which I want the user to be able to scroll around by moving the mouse to the edge of the screen (like in most strategy games with a top-down map).
To do this I am resetting the 'value' on the scroll bar using a timer that ticks rapidly to set the value of the scroll bar according to the location of the mouse on the screen:
I feel the above is a very messy way of doing this and there must be a much cleaner way of basically simulating the click/drag scrolling functionality of the scroll bar using code.
By simply setting the value in this way I find as it scrolls it is not smooth at all and the image has these blips of horrible white background (panel background) appearing as it's trying to keep up with the constant changing.
I'm fascinated to know how the clicking & dragging works in such a way as for it to remain completely smooth and to find out if there's a way I can simulate that using code!
A technique that I once used was having 3 BufferedImages A, B and C, each representing the full scene. My JPanel used A to draw, and a Thread used either B or C to draw the scene. When done, it set A to either of the two and then gave the JPanel a sign to redraw. The advantage was that that thread had the full xx milliseconds to draw the scene. All the panel had to do was to draw A.
There were some synchronization issues IIRC, and I used it to drag the scene with the mouse, not to scroll as you wrote. But that shouldn't matter.
There are three kinds of actuaries: those who can count, and those who can't.
2. Don't use a TimerTask. The creation and updates to the model of a component should be done on the Event Dispatch Thread (EDT). Instead you should be using a Swing Timer.
3. Check out the JComponent.setAutoscrolls(...) method. It has an example of a MouseListener that allows scrolling to continue once the mouse is dragged outside of the bounds of the scroll pane. Maybe look at the source code to see what this method does and see if you can replicate the behaviour for your requirement.
Curse your sudden but inevitable betrayal! And this tiny ad too!