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?
It is scrollpane's horizontal scrollbar child. It displays policy for the horizontal scrollbar. This displays the lower left corner. This displays in the lower right corner.
What is the difference between a Scrollbar and a JScrollPane ? A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
Just use the reference to your JScrollPane object, get the vertical scroll bar from it using getVerticalScrollBar , and then call setUnitIncrement on it, like this: myJScrollPane. getVerticalScrollBar(). setUnitIncrement(16);
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With