views:

798

answers:

3

How would I go about writing my own scrollbar using standard Java 2D.

I really don't want to use swing, and I've already made up my own component parts for everything else such as buttons etc.

I'm not really looking for code, rather the math involved in the event changes and the drawing.

+2  A: 

Why on earth would you want to write your own java GUI toolkit? You already have the choice of Swing and SWT, can you really do better than these two teams?

If you've already written the rest of the toolkit, I don't understand why the scrollbar would stump you. Without knowing anything about your event system, or how your custom components are structured, it's impossible to give much advise. I don't see this being particularly maths intensive - just maintain the height of the scrollable component, and the view it's in, and the scrollbar size should match the proportion of the component that is visible. The position of the scrollbar should match which part of the component is visible (this will have to be scaled). Specifically, what do you want to know?

Draemon
Swing is bloated and uses Vector internally. It is certainly not the best in terms of optimized code.Opinion: SWT has an even worse programming model than Swing. Both leave a lot to be desired.
MetroidFan2002
Perhaps, but the end-user experience of modern swing apps is arguably just as good as anything else, which leaves very little justification for writing an entire GUI framework yourself. It's still very unlikely you'd do better. It depends how/where it uses Vector as to whether this is bad.
Draemon
+1  A: 

Java is now open. I'd go look at the source for the Swing and/or SWT as they are already implemented. The math seems fairly straight forward. You have a Bar and a Container. To simplify we will only discuss length (the dimension in which the scrollbar moves). The container is of a certain length. The bar is of a length that is equal to or less than the container. It is useful to define the center and the two endpoints of the scrollbar. You can have the scrollbar start at 0 at the top and 1 at the bottom or 0 at the top and 100 at the bottom with the important part being defining your scrollbar in the same manner. Then you can check the endpoints for collision with the edge to stop the bar from moving. If the mouse is held down with the cursor over the coordinates inside the bar, the bar starts caring about where the cursor is and will paint the scrollbar and whatever the scrollbar is ultimately supposed to be affecting. So, you would take the page to be affected and map it to 0 and 1 * the scale in pixels of the scrollbar. Then you get to worry about the arrows at either end and how big of a jump each click is and dealing with mousedown events etc.etc. Use what is given don't reinvent the wheel.

Ichorus
A: 

While not Java2D, this straightforward code snippet might help:

http://processing.org/learning/topics/scrollbar.html

jedierikb