Scrollable JDesktopPane?
Asked Answered
S

3

13

I'd like to add scrolling capability to a javax.swing.JDesktopPane. But wrapping in a javax.swing.JScrollPane does not produce the desired behavior.

Searching the web shows that this has been an issue for quite some time. There are some solutions out there, but they seem to be pretty old, and I'm not not completely satisfied with them.

What actively maintained solutions do you know?

Stoic answered 29/9, 2008 at 13:51 Comment(0)
A
8

I've used JavaWorld's solution by creating my own JScrollableDesktopPane.

Actinic answered 29/9, 2008 at 13:56 Comment(1)
That's actually my current solution too, but I'm not thrilled with it. I decided to ask here before embarking on my own project to create one that I like.Stoic
C
4

Javaworld's JScrollableDesktopPane is no longer available on their website. I managed to scrounge up some copies of it but none of them work.

A simple solution I've derived can be achieved doing something like the following. It's not the prettiest but it certainly works better than the default behavior.

public class Window extends Frame {
    JScrollPane scrollContainer = new JScrollPane();
    JDesktopPane mainWorkingPane = new JDesktopPane();

    public Window() {
        scrollContainer.setViewportView(mainWorkingPane);

        addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent evt) {
                revalidateDesktopPane();
            }
        });
    }

    private void revalidateDesktopPane() {
        Dimension dim = new Dimension(0,0);
        Component[] com = mainWorkingPane.getComponents();
        for (int i=0 ; i<com.length ; i++) {
            int w = (int) dim.getWidth()+com[i].getWidth();
            int h = (int) dim.getHeight()+com[i].getHeight();
            dim.setSize(new Dimension(w,h));
        }
        mainWorkingPane.setPreferredSize(dim);
        mainWorkingPane.revalidate();
        revalidate();
        repaint();  
    }
}

The idea being to wrap JDesktopPane in a JScrollPane, add a resize listener on the main Frame and then evaluate the contents of the JDesktopPane on resize (or adding new elements).

Hope this helps someone out there.

Cub answered 29/9, 2008 at 13:51 Comment(1)
I needed to tweak the dimension calculations and add the listener to other component events but this code works for me.Unterwalden
V
1

I've found this : http://www.javaworld.com/javaworld/jw-11-2001/jw-1130-jscroll.html?page=1

It's a nice tutorial with lots of explanations and infos on Swing & so, which permits to create a JscrollableDesktopPane with lots of stuff.

You will need to modify a bit some parts of code to fulfill your requirements.

Enjoy !

Vandusen answered 29/9, 2008 at 13:51 Comment(1)
Oops, forgetting the direct link to the source : javaworld.com/javaworld/jw-11-2001/jscroll/jw-1130-jscroll.jarVandusen

© 2022 - 2024 — McMap. All rights reserved.