views:

1521

answers:

3

Hi, I have a JScrollPane with FlowLayout that I want to have a fixed width. It should be scrolling vertically only, and the contents should be rearranged automatically when I resize the window. I think there should be a method like setEnableHorizontalScroll(false) but can't find it. Is there any easy way to do this?

+1  A: 

You can use:

import static javax.swing.ScrollPaneConstants.*;
// ...
JScrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);

...but this just prevents the horizontal scrollbar from ever being shown.

To get the contents to rearrange automatically will depend on what the content is. A JTextPane or JEditorPane will do this for you automatically (without the need for the above code).

Matthew Murdoch
The contents are `JPanel`s of fixed size, and they are not auto rearranged. The scrollbar simply disappear :(
phunehehe
+2  A: 

This is no custom solution out of the box in the JDK.

You can use the WrapLayout.

Or you can create a custom panel and implement the Scrollable interface. The key in this case is overriding getScrollableTracksViewportWidth() to return true, so the viewports width and not the width of the panel is used for layout purposes. An example of this approach can be found in the ScrollableFlowPanel

camickr
I don't like the idea of using a third party library. Java should have that by default I think.But thanks for sharing, it does what I need already :)
phunehehe
A: 

Finally I found out how, please see this very short example, no advanced tricks needed:

public class MyTest extends JFrame {

    public static void main(String[] args) {
        MyTest test = new MyTest();
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        test.setSize(300, 200);
        test.setVisible(true);
    }

    public MyTest() {
        String[] data = {
            "Arlo", "Cosmo", "Elmo", "Hugo",
            "Jethro", "Laszlo", "Milo", "Nemo",
            "Otto", "Ringo", "Rocco", "Rollo"
        };
        JList list = new JList(data);
        list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
        list.setVisibleRowCount(0);
        JScrollPane scroll = new JScrollPane(list);
        this.add(scroll);
    }
}

Adapted from Sun's tutorial

phunehehe